Merge
authorpsadhukhan
Wed, 12 Jun 2019 10:02:49 +0530
changeset 55372 5d5fccc4fd3f
parent 55371 9cb499911646 (current diff)
parent 55337 ae3dbc712839 (diff)
child 55373 59642852dee0
Merge
src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs-11v2-20a3.h
test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/GCTest.java
test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java
test/langtools/tools/javac/diags/examples/BreakComplexValueNoSwitchExpression.java
test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java
test/langtools/tools/javac/diags/examples/BreakMissingValue.java
--- a/make/jdk/src/classes/build/tools/fixuppandoc/Main.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/make/jdk/src/classes/build/tools/fixuppandoc/Main.java	Wed Jun 12 10:02:49 2019 +0530
@@ -44,6 +44,7 @@
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 /**
@@ -63,11 +64,18 @@
  *
  * <h2>Tables: row headings</h2>
  *
- * {@code scope="row"} is added to the {@code <td>} elements in the first
- * column whose cell contents are all different and therefore which can be
- * used to identify the row. In case of ambiguity, a column containing
- * a {@code <th>} whose contents begin <em>name</em> is preferred.
+ * For simple tables, as typically generated by _pandoc_, determine the column
+ * whose contents are unique, and convert the cells in that column to be header
+ * cells with {@code scope="row"}. In case of ambiguity, a column containing a
+ * {@code <th>} whose contents begin with <em>name</em> is preferred.
+ * When converting the cell, the {@code style} attribute will be updated to
+ * specify {@code font-weight: normal}, and if there is not already an explicit
+ * setting for {@code text-align}, then the style will be updated to include
+ * {@code text-align:left;}.
  *
+ * These rules do not apply if the table contains any cells that include
+ * a setting for the {@code scope} attribute, or if the table contains
+ * spanning cells or nested tables.
  *
  * <h2>{@code <meta name="generator">}</h2>
  *
@@ -533,12 +541,39 @@
                 }
                 index++;
             }
+            boolean updateEndTd = false;
+            Pattern styleAttr = Pattern.compile("(?<before>.*style=\")(?<style>[^\"]*)(?<after>\".*)");
             for (Entry e : entries) {
                 if (simple && e.column == maxIndex) {
-                    out.write(e.html.substring(0, e.html.length() - 1));
-                    out.write(" scope=\"row\">");
+                    String attrs = e.html.substring(3, e.html.length() - 1);
+                    out.write("<th");
+                    Matcher m = styleAttr.matcher(attrs);
+                    if (m.matches()) {
+                        out.write(m.group("before"));
+                        out.write("font-weight: normal; ");
+                        String style = m.group("style");
+                        if (!style.contains("text-align")) {
+                            out.write("text-align: left; ");
+                        }
+                        out.write(style);
+                        out.write(m.group("after"));
+                    } else {
+                        out.write(" style=\"font-weight: normal; text-align:left;\" ");
+                        out.write(attrs);
+                    }
+                    out.write(" scope=\"row\"");
+                    out.write(">");
+                    updateEndTd = true;
+                } else if (updateEndTd && e.html.equalsIgnoreCase("</td>")) {
+                    out.write("</th>");
+                    updateEndTd = false;
                 } else {
                     out.write(e.html);
+                    if (updateEndTd && e.html.regionMatches(true, 0, "<td", 0, 3)) {
+                        // a new cell has been started without explicitly closing the
+                        // cell that was being updated
+                        updateEndTd = false;
+                    }
                 }
             }
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/cpu/aarch64/aarch64-asmtest.py	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,1177 @@
+import random
+
+AARCH64_AS = "<PATH-TO-AS>"
+AARCH64_OBJDUMP = "<PATH-TO-OBJDUMP>"
+AARCH64_OBJCOPY = "<PATH-TO-OBJCOPY>"
+
+class Operand(object):
+
+     def generate(self):
+        return self
+
+class Register(Operand):
+
+    def generate(self):
+        self.number = random.randint(0, 30)
+        return self
+
+    def astr(self, prefix):
+        return prefix + str(self.number)
+
+class FloatRegister(Register):
+
+    def __str__(self):
+        return self.astr("v")
+
+    def nextReg(self):
+        next = FloatRegister()
+        next.number = (self.number + 1) % 32
+        return next
+
+class GeneralRegister(Register):
+
+    def __str__(self):
+        return self.astr("r")
+
+class GeneralRegisterOrZr(Register):
+
+    def generate(self):
+        self.number = random.randint(0, 31)
+        return self
+
+    def astr(self, prefix = ""):
+        if (self.number == 31):
+            return prefix + "zr"
+        else:
+            return prefix + str(self.number)
+
+    def __str__(self):
+        if (self.number == 31):
+            return self.astr()
+        else:
+            return self.astr("r")
+
+class GeneralRegisterOrSp(Register):
+    def generate(self):
+        self.number = random.randint(0, 31)
+        return self
+
+    def astr(self, prefix = ""):
+        if (self.number == 31):
+            return "sp"
+        else:
+            return prefix + str(self.number)
+
+    def __str__(self):
+        if (self.number == 31):
+            return self.astr()
+        else:
+            return self.astr("r")
+
+class FloatZero(Operand):
+
+    def __str__(self):
+        return "0.0"
+
+    def astr(self, ignored):
+        return "#0.0"
+
+class OperandFactory:
+
+    _modes = {'x' : GeneralRegister,
+              'w' : GeneralRegister,
+              's' : FloatRegister,
+              'd' : FloatRegister,
+              'z' : FloatZero}
+
+    @classmethod
+    def create(cls, mode):
+        return OperandFactory._modes[mode]()
+
+class ShiftKind:
+
+    def generate(self):
+        self.kind = ["LSL", "LSR", "ASR"][random.randint(0,2)]
+        return self
+
+    def cstr(self):
+        return self.kind
+
+class Instruction(object):
+
+    def __init__(self, name):
+        self._name = name
+        self.isWord = name.endswith("w") | name.endswith("wi")
+        self.asmRegPrefix = ["x", "w"][self.isWord]
+
+    def aname(self):
+        if (self._name.endswith("wi")):
+            return self._name[:len(self._name)-2]
+        else:
+            if (self._name.endswith("i") | self._name.endswith("w")):
+                return self._name[:len(self._name)-1]
+            else:
+                return self._name
+
+    def emit(self) :
+        pass
+
+    def compare(self) :
+        pass
+
+    def generate(self) :
+        return self
+
+    def cstr(self):
+        return '__ %s(' % self.name()
+
+    def astr(self):
+        return '%s\t' % self.aname()
+
+    def name(self):
+        name = self._name
+        if name == "and":
+            name = "andr" # Special case: the name "and" can't be used
+                          # in HotSpot, even for a member.
+        return name
+
+    def multipleForms(self):
+         return 0
+
+class InstructionWithModes(Instruction):
+
+    def __init__(self, name, mode):
+        Instruction.__init__(self, name)
+        self.mode = mode
+        self.isFloat = (mode == 'd') | (mode == 's')
+        if self.isFloat:
+            self.isWord = mode != 'd'
+            self.asmRegPrefix = ["d", "s"][self.isWord] 
+        else:
+            self.isWord = mode != 'x'
+            self.asmRegPrefix = ["x", "w"][self.isWord]
+       
+    def name(self):
+        return self._name + (self.mode if self.mode != 'x' else '')
+            
+    def aname(self):
+        return (self._name+mode if (mode == 'b' or mode == 'h') 
+            else self._name)
+
+class ThreeRegInstruction(Instruction):
+
+    def generate(self):
+        self.reg = [GeneralRegister().generate(), GeneralRegister().generate(),
+                    GeneralRegister().generate()]
+        return self
+
+
+    def cstr(self):
+        return (super(ThreeRegInstruction, self).cstr()
+                + ('%s, %s, %s' 
+                   % (self.reg[0],
+                      self.reg[1], self.reg[2])))
+                
+    def astr(self):
+        prefix = self.asmRegPrefix
+        return (super(ThreeRegInstruction, self).astr()
+                + ('%s, %s, %s' 
+                   % (self.reg[0].astr(prefix),
+                      self.reg[1].astr(prefix), self.reg[2].astr(prefix))))
+                
+class FourRegInstruction(ThreeRegInstruction):
+
+    def generate(self):
+        self.reg = ThreeRegInstruction.generate(self).reg + [GeneralRegister().generate()]
+        return self
+
+
+    def cstr(self):
+        return (super(FourRegInstruction, self).cstr()
+                + (', %s' % self.reg[3]))
+                
+    def astr(self):
+        prefix = self.asmRegPrefix
+        return (super(FourRegInstruction, self).astr()
+                + (', %s' % self.reg[3].astr(prefix)))
+                
+class TwoRegInstruction(Instruction):
+
+    def generate(self):
+        self.reg = [GeneralRegister().generate(), GeneralRegister().generate()]
+        return self
+
+    def cstr(self):
+        return (super(TwoRegInstruction, self).cstr()
+                + '%s, %s' % (self.reg[0],
+                              self.reg[1]))
+
+    def astr(self):
+        prefix = self.asmRegPrefix
+        return (super(TwoRegInstruction, self).astr()
+                + ('%s, %s' 
+                   % (self.reg[0].astr(prefix),
+                      self.reg[1].astr(prefix))))
+                
+class TwoRegImmedInstruction(TwoRegInstruction):
+
+    def generate(self):
+        super(TwoRegImmedInstruction, self).generate()
+        self.immed = random.randint(0, 1<<11 -1)
+        return self
+        
+    def cstr(self):
+        return (super(TwoRegImmedInstruction, self).cstr()
+                + ', %su' % self.immed)
+
+    def astr(self):
+        return (super(TwoRegImmedInstruction, self).astr()
+                + ', #%s' % self.immed)
+
+class OneRegOp(Instruction):
+
+    def generate(self):
+        self.reg = GeneralRegister().generate()
+        return self
+
+    def cstr(self):
+        return (super(OneRegOp, self).cstr()
+                + '%s);' % self.reg)
+
+    def astr(self):
+        return (super(OneRegOp, self).astr()
+                + '%s' % self.reg.astr(self.asmRegPrefix))
+
+class ArithOp(ThreeRegInstruction):
+
+    def generate(self):
+        super(ArithOp, self).generate()
+        self.kind = ShiftKind().generate()
+        self.distance = random.randint(0, (1<<5)-1 if self.isWord else (1<<6)-1)
+        return self
+        
+    def cstr(self):
+        return ('%s, Assembler::%s, %s);' 
+                % (ThreeRegInstruction.cstr(self),
+                   self.kind.cstr(), self.distance))
+
+    def astr(self):
+        return ('%s, %s #%s'
+                % (ThreeRegInstruction.astr(self),
+                   self.kind.cstr(),
+                   self.distance))
+
+class AddSubCarryOp(ThreeRegInstruction):
+    
+    def cstr(self):
+        return ('%s);' 
+                % (ThreeRegInstruction.cstr(self)))
+
+class AddSubExtendedOp(ThreeRegInstruction):
+
+    uxtb, uxth, uxtw, uxtx, sxtb, sxth, sxtw, sxtx = range(8)
+    optNames = ["uxtb", "uxth", "uxtw", "uxtx", "sxtb", "sxth", "sxtw", "sxtx"]
+
+    def generate(self):
+        super(AddSubExtendedOp, self).generate()
+        self.amount = random.randint(1, 4)
+        self.option = random.randint(0, 7)
+        return self
+
+    def cstr(self):
+        return (super(AddSubExtendedOp, self).cstr()
+                + (", ext::" + AddSubExtendedOp.optNames[self.option] 
+                   + ", " + str(self.amount) + ");"))
+                
+    def astr(self):
+        return (super(AddSubExtendedOp, self).astr()
+                + (", " + AddSubExtendedOp.optNames[self.option] 
+                   + " #" + str(self.amount)))
+
+class AddSubImmOp(TwoRegImmedInstruction):
+
+    def cstr(self):
+         return super(AddSubImmOp, self).cstr() + ");"
+    
+class LogicalImmOp(AddSubImmOp):
+
+     # These tables are legal immediate logical operands
+     immediates32 \
+         = [0x1, 0x3f, 0x1f0, 0x7e0, 
+            0x1c00, 0x3ff0, 0x8000, 0x1e000, 
+            0x3e000, 0x78000, 0xe0000, 0x100000, 
+            0x1fffe0, 0x3fe000, 0x780000, 0x7ffff8, 
+            0xff8000, 0x1800180, 0x1fffc00, 0x3c003c0, 
+            0x3ffff00, 0x7c00000, 0x7fffe00, 0xf000f00, 
+            0xfffe000, 0x18181818, 0x1ffc0000, 0x1ffffffe, 
+            0x3f003f00, 0x3fffe000, 0x60006000, 0x7f807f80, 
+            0x7ffffc00, 0x800001ff, 0x803fffff, 0x9f9f9f9f, 
+            0xc0000fff, 0xc0c0c0c0, 0xe0000000, 0xe003e003, 
+            0xe3ffffff, 0xf0000fff, 0xf0f0f0f0, 0xf80000ff, 
+            0xf83ff83f, 0xfc00007f, 0xfc1fffff, 0xfe0001ff, 
+            0xfe3fffff, 0xff003fff, 0xff800003, 0xff87ff87, 
+            0xffc00fff, 0xffe0000f, 0xffefffef, 0xfff1fff1, 
+            0xfff83fff, 0xfffc0fff, 0xfffe0fff, 0xffff3fff, 
+            0xffffc007, 0xffffe1ff, 0xfffff80f, 0xfffffe07, 
+            0xffffffbf, 0xfffffffd]
+
+     immediates \
+         = [0x1, 0x1f80, 0x3fff0, 0x3ffffc, 
+            0x3fe0000, 0x1ffc0000, 0xf8000000, 0x3ffffc000, 
+            0xffffffe00, 0x3ffffff800, 0xffffc00000, 0x3f000000000, 
+            0x7fffffff800, 0x1fe000001fe0, 0x3ffffff80000, 0xc00000000000, 
+            0x1ffc000000000, 0x3ffff0003ffff, 0x7ffffffe00000, 0xfffffffffc000, 
+            0x1ffffffffffc00, 0x3fffffffffff00, 0x7ffffffffffc00, 0xffffffffff8000, 
+            0x1ffffffff800000, 0x3fffffc03fffffc, 0x7fffc0000000000, 0xff80ff80ff80ff8, 
+            0x1c00000000000000, 0x1fffffffffff0000, 0x3fffff803fffff80, 0x7fc000007fc00000, 
+            0x8000000000000000, 0x803fffff803fffff, 0xc000007fc000007f, 0xe00000000000ffff, 
+            0xe3ffffffffffffff, 0xf007f007f007f007, 0xf80003ffffffffff, 0xfc000003fc000003, 
+            0xfe000000007fffff, 0xff00000000007fff, 0xff800000000003ff, 0xffc00000000000ff, 
+            0xffe00000000003ff, 0xfff0000000003fff, 0xfff80000001fffff, 0xfffc0000fffc0000, 
+            0xfffe003fffffffff, 0xffff3fffffffffff, 0xffffc0000007ffff, 0xffffe01fffffe01f, 
+            0xfffff800000007ff, 0xfffffc0fffffffff, 0xffffff00003fffff, 0xffffffc0000007ff, 
+            0xfffffff0000001ff, 0xfffffffc00003fff, 0xffffffff07ffffff, 0xffffffffe003ffff, 
+            0xfffffffffc01ffff, 0xffffffffffc00003, 0xfffffffffffc000f, 0xffffffffffffe07f]
+
+     def generate(self):
+          AddSubImmOp.generate(self)
+          self.immed = \
+              self.immediates32[random.randint(0, len(self.immediates32)-1)] \
+              	if self.isWord \
+              else \
+              	self.immediates[random.randint(0, len(self.immediates)-1)]
+              
+          return self
+                  
+     def astr(self):
+          return (super(TwoRegImmedInstruction, self).astr()
+                  + ', #0x%x' % self.immed)
+
+     def cstr(self):
+          return super(AddSubImmOp, self).cstr() + "l);"
+    
+class MultiOp():
+
+    def multipleForms(self):
+         return 3
+
+    def forms(self):
+         return ["__ pc()", "back", "forth"]
+
+    def aforms(self):
+         return [".", "back", "forth"]
+
+class AbsOp(MultiOp, Instruction):
+
+    def cstr(self):
+        return super(AbsOp, self).cstr() + "%s);"
+
+    def astr(self):
+        return Instruction.astr(self) + "%s"
+
+class RegAndAbsOp(MultiOp, Instruction):
+    
+    def multipleForms(self):
+        if self.name() == "adrp": 
+            # We can only test one form of adrp because anything other
+            # than "adrp ." requires relocs in the assembler output
+            return 1
+        return 3
+
+    def generate(self):
+        Instruction.generate(self)
+        self.reg = GeneralRegister().generate()
+        return self
+    
+    def cstr(self):
+        if self.name() == "adrp":
+            return "__ _adrp(" + "%s, %s);" % (self.reg, "%s")
+        return (super(RegAndAbsOp, self).cstr() 
+                + "%s, %s);" % (self.reg, "%s"))
+
+    def astr(self):
+        return (super(RegAndAbsOp, self).astr()
+                + self.reg.astr(self.asmRegPrefix) + ", %s")
+
+class RegImmAbsOp(RegAndAbsOp):
+    
+    def cstr(self):
+        return (Instruction.cstr(self)
+                + "%s, %s, %s);" % (self.reg, self.immed, "%s"))
+
+    def astr(self):
+        return (Instruction.astr(self)
+                + ("%s, #%s, %s" 
+                   % (self.reg.astr(self.asmRegPrefix), self.immed, "%s")))
+
+    def generate(self):
+        super(RegImmAbsOp, self).generate()
+        self.immed = random.randint(0, 1<<5 -1)
+        return self
+
+class MoveWideImmOp(RegImmAbsOp):
+    
+    def multipleForms(self):
+         return 0
+
+    def cstr(self):
+        return (Instruction.cstr(self)
+                + "%s, %s, %s);" % (self.reg, self.immed, self.shift))
+
+    def astr(self):
+        return (Instruction.astr(self)
+                + ("%s, #%s, lsl %s" 
+                   % (self.reg.astr(self.asmRegPrefix), 
+                      self.immed, self.shift)))
+
+    def generate(self):
+        super(RegImmAbsOp, self).generate()
+        self.immed = random.randint(0, 1<<16 -1)
+        if self.isWord:
+            self.shift = random.randint(0, 1) * 16
+        else:
+            self.shift = random.randint(0, 3) * 16
+        return self
+
+class BitfieldOp(TwoRegInstruction):
+    
+    def cstr(self):
+        return (Instruction.cstr(self)
+                + ("%s, %s, %s, %s);"
+                   % (self.reg[0], self.reg[1], self.immr, self.imms)))
+
+    def astr(self):
+        return (TwoRegInstruction.astr(self)
+                + (", #%s, #%s"
+                   % (self.immr, self.imms)))
+
+    def generate(self):
+        TwoRegInstruction.generate(self)
+        self.immr = random.randint(0, 31)
+        self.imms = random.randint(0, 31)
+        return self
+
+class ExtractOp(ThreeRegInstruction):
+
+    def generate(self):
+        super(ExtractOp, self).generate()
+        self.lsb = random.randint(0, (1<<5)-1 if self.isWord else (1<<6)-1)
+        return self
+
+    def cstr(self):
+        return (ThreeRegInstruction.cstr(self)
+                + (", %s);" % self.lsb))
+    
+    def astr(self):
+        return (ThreeRegInstruction.astr(self)
+                + (", #%s" % self.lsb))
+    
+class CondBranchOp(MultiOp, Instruction):
+
+    def cstr(self):
+        return "__ br(Assembler::" + self.name() + ", %s);"
+        
+    def astr(self):
+        return "b." + self.name() + "\t%s"
+
+class ImmOp(Instruction):
+
+    def cstr(self):
+        return "%s%s);" % (Instruction.cstr(self), self.immed)
+        
+    def astr(self):
+        return Instruction.astr(self) + "#" + str(self.immed)
+        
+    def generate(self):
+        self.immed = random.randint(0, 1<<16 -1)
+        return self
+
+class Op(Instruction):
+
+    def cstr(self):
+        return Instruction.cstr(self) + ");"
+
+class SystemOp(Instruction):
+
+     def __init__(self, op):
+          Instruction.__init__(self, op[0])
+          self.barriers = op[1]
+
+     def generate(self):
+          Instruction.generate(self)
+          self.barrier \
+              = self.barriers[random.randint(0, len(self.barriers)-1)]
+          return self
+
+     def cstr(self):
+          return Instruction.cstr(self) + "Assembler::" + self.barrier + ");"
+
+     def astr(self):
+          return Instruction.astr(self) + self.barrier
+
+conditionCodes = ["EQ", "NE", "HS", "CS", "LO", "CC", "MI", "PL", "VS", \
+                       "VC", "HI", "LS", "GE", "LT", "GT", "LE", "AL", "NV"]
+
+class ConditionalCompareOp(TwoRegImmedInstruction):
+
+    def generate(self):
+        TwoRegImmedInstruction.generate(self)
+        self.cond = random.randint(0, 15)
+        self.immed = random.randint(0, 15)
+        return self
+
+    def cstr(self):
+        return (super(ConditionalCompareOp, self).cstr() + ", " 
+                + "Assembler::" + conditionCodes[self.cond] + ");")
+
+    def astr(self):
+        return (super(ConditionalCompareOp, self).astr() + 
+                 ", " + conditionCodes[self.cond])
+
+class ConditionalCompareImmedOp(Instruction):
+
+    def generate(self):
+        self.reg = GeneralRegister().generate()
+        self.cond = random.randint(0, 15)
+        self.immed2 = random.randint(0, 15)
+        self.immed = random.randint(0, 31)
+        return self
+
+    def cstr(self):
+        return (Instruction.cstr(self) + str(self.reg) + ", "
+                + str(self.immed) + ", "
+                + str(self.immed2) + ", "
+                + "Assembler::" + conditionCodes[self.cond] + ");")
+
+    def astr(self):
+        return (Instruction.astr(self) 
+                + self.reg.astr(self.asmRegPrefix) 
+                + ", #" + str(self.immed)
+                + ", #" + str(self.immed2)
+                + ", " + conditionCodes[self.cond])
+
+class TwoRegOp(TwoRegInstruction):
+    
+    def cstr(self):
+        return TwoRegInstruction.cstr(self) + ");"
+
+class ThreeRegOp(ThreeRegInstruction):
+    
+    def cstr(self):
+        return ThreeRegInstruction.cstr(self) + ");"
+
+class FourRegMulOp(FourRegInstruction):
+    
+    def cstr(self):
+        return FourRegInstruction.cstr(self) + ");"
+
+    def astr(self):
+        isMaddsub = self.name().startswith("madd") | self.name().startswith("msub")
+        midPrefix = self.asmRegPrefix if isMaddsub else "w"
+        return (Instruction.astr(self) 
+                + self.reg[0].astr(self.asmRegPrefix) 
+                + ", " + self.reg[1].astr(midPrefix) 
+                + ", " + self.reg[2].astr(midPrefix)
+                + ", " + self.reg[3].astr(self.asmRegPrefix))
+
+class ConditionalSelectOp(ThreeRegInstruction):
+
+    def generate(self):
+        ThreeRegInstruction.generate(self)
+        self.cond = random.randint(0, 15)
+        return self
+
+    def cstr(self):
+        return (ThreeRegInstruction.cstr(self) + ", "
+                + "Assembler::" + conditionCodes[self.cond] + ");")
+
+    def astr(self):
+        return (ThreeRegInstruction.astr(self) 
+                + ", " + conditionCodes[self.cond])    
+
+class LoadStoreExclusiveOp(InstructionWithModes):
+
+    def __init__(self, op): # op is a tuple of ["name", "mode", registers]
+        InstructionWithModes.__init__(self, op[0], op[1])
+        self.num_registers = op[2]
+
+    def astr(self):
+        result = self.aname() + '\t'
+        regs = list(self.regs)
+        index = regs.pop() # The last reg is the index register
+        prefix = ('x' if (self.mode == 'x') 
+                  & ((self.name().startswith("ld"))
+                     | (self.name().startswith("stlr"))) # Ewww :-(
+                  else 'w')
+        result = result + regs.pop(0).astr(prefix) + ", "
+        for s in regs:
+            result = result + s.astr(self.asmRegPrefix) + ", "
+        result = result + "[" + index.astr("x") + "]"
+        return result
+
+    def cstr(self):
+        result = InstructionWithModes.cstr(self)
+        regs = list(self.regs)
+        index = regs.pop() # The last reg is the index register
+        for s in regs:
+            result = result + str(s) + ", "
+        result = result + str(index) + ");"
+        return result
+
+    def appendUniqueReg(self):
+        result = 0
+        while result == 0:
+            newReg = GeneralRegister().generate()
+            result = 1
+            for i in self.regs:
+                result = result and (i.number != newReg.number)
+        self.regs.append(newReg)
+
+    def generate(self):
+        self.regs = []
+        for i in range(self.num_registers):
+            self.appendUniqueReg()
+        return self
+
+    def name(self):
+        if self.mode == 'x':
+            return self._name
+        else:
+            return self._name + self.mode
+
+    def aname(self):
+        if (self.mode == 'b') | (self.mode == 'h'):
+            return self._name + self.mode
+        else:
+            return self._name
+
+class Address(object):
+    
+    base_plus_unscaled_offset, pre, post, base_plus_reg, \
+        base_plus_scaled_offset, pcrel, post_reg, base_only = range(8)
+    kinds = ["base_plus_unscaled_offset", "pre", "post", "base_plus_reg", 
+             "base_plus_scaled_offset", "pcrel", "post_reg", "base_only"]
+    extend_kinds = ["uxtw", "lsl", "sxtw", "sxtx"]
+
+    @classmethod
+    def kindToStr(cls, i):
+         return cls.kinds[i]
+    
+    def generate(self, kind, shift_distance):
+        self.kind = kind
+        self.base = GeneralRegister().generate()
+        self.index = GeneralRegister().generate()
+        self.offset = {
+            Address.base_plus_unscaled_offset: random.randint(-1<<8, 1<<8-1) | 1,
+            Address.pre: random.randint(-1<<8, 1<<8-1),
+            Address.post: random.randint(-1<<8, 1<<8-1),
+            Address.pcrel: random.randint(0, 2),
+            Address.base_plus_reg: 0,
+            Address.base_plus_scaled_offset: (random.randint(0, 1<<11-1) | (3 << 9))*8,
+            Address.post_reg: 0,
+            Address.base_only: 0} [kind]
+        self.offset >>= (3 - shift_distance)
+        self.extend_kind = Address.extend_kinds[random.randint(0, 3)]
+        self.shift_distance = random.randint(0, 1) * shift_distance
+        return self
+
+    def __str__(self):
+        result = {
+            Address.base_plus_unscaled_offset: "Address(%s, %s)" \
+                % (str(self.base), self.offset),
+            Address.pre: "Address(__ pre(%s, %s))" % (str(self.base), self.offset),
+            Address.post: "Address(__ post(%s, %s))" % (str(self.base), self.offset),
+            Address.post_reg: "Address(__ post(%s, %s))" % (str(self.base), self.index),
+            Address.base_only: "Address(%s)" % (str(self.base)),
+            Address.pcrel: "",
+            Address.base_plus_reg: "Address(%s, %s, Address::%s(%s))" \
+                % (self.base, self.index, self.extend_kind, self.shift_distance),
+            Address.base_plus_scaled_offset: 
+            "Address(%s, %s)" % (self.base, self.offset) } [self.kind]
+        if (self.kind == Address.pcrel):
+            result = ["__ pc()", "back", "forth"][self.offset]
+        return result
+
+    def astr(self, prefix):
+        extend_prefix = prefix
+        if self.kind == Address.base_plus_reg:
+            if self.extend_kind.endswith("w"):
+                extend_prefix = "w"
+        result = {
+            Address.base_plus_unscaled_offset: "[%s, %s]" \
+                 % (self.base.astr(prefix), self.offset),
+            Address.pre: "[%s, %s]!" % (self.base.astr(prefix), self.offset),
+            Address.post: "[%s], %s" % (self.base.astr(prefix), self.offset),
+            Address.post_reg: "[%s], %s" % (self.base.astr(prefix), self.index.astr(prefix)),
+            Address.base_only: "[%s]" %  (self.base.astr(prefix)),
+            Address.pcrel: "",
+            Address.base_plus_reg: "[%s, %s, %s #%s]" \
+                % (self.base.astr(prefix), self.index.astr(extend_prefix), 
+                   self.extend_kind, self.shift_distance),
+            Address.base_plus_scaled_offset: \
+                "[%s, %s]" \
+                % (self.base.astr(prefix), self.offset)
+            } [self.kind]
+        if (self.kind == Address.pcrel):
+            result = [".", "back", "forth"][self.offset]
+        return result
+        
+class LoadStoreOp(InstructionWithModes):
+
+    def __init__(self, args):
+        name, self.asmname, self.kind, mode = args
+        InstructionWithModes.__init__(self, name, mode)
+
+    def generate(self):
+
+        # This is something of a kludge, but the offset needs to be
+        # scaled by the memory datamode somehow.
+        shift = 3
+        if (self.mode == 'b') | (self.asmname.endswith("b")):
+            shift = 0
+        elif (self.mode == 'h') | (self.asmname.endswith("h")):
+            shift = 1
+        elif (self.mode == 'w') | (self.asmname.endswith("w")) \
+                | (self.mode == 's') :
+            shift = 2
+
+        self.adr = Address().generate(self.kind, shift)
+
+        isFloat = (self.mode == 'd') | (self.mode == 's')
+
+        regMode = FloatRegister if isFloat else GeneralRegister
+        self.reg = regMode().generate()
+        return self
+
+    def cstr(self):
+        if not(self._name.startswith("prfm")):
+            return "%s%s, %s);" % (Instruction.cstr(self), str(self.reg), str(self.adr))
+        else: # No target register for a prefetch
+            return "%s%s);" % (Instruction.cstr(self), str(self.adr))
+
+    def astr(self):
+        if not(self._name.startswith("prfm")):
+            return "%s\t%s, %s" % (self.aname(), self.reg.astr(self.asmRegPrefix),
+                                     self.adr.astr("x"))
+        else: # No target register for a prefetch
+            return "%s %s" % (self.aname(),
+                                     self.adr.astr("x"))
+
+    def aname(self):
+         result = self.asmname
+         # if self.kind == Address.base_plus_unscaled_offset:
+         #      result = result.replace("ld", "ldu", 1)
+         #      result = result.replace("st", "stu", 1)
+         return result
+
+class LoadStorePairOp(InstructionWithModes):
+
+     numRegs = 2
+     
+     def __init__(self, args):
+          name, self.asmname, self.kind, mode = args
+          InstructionWithModes.__init__(self, name, mode)
+          self.offset = random.randint(-1<<4, 1<<4-1) << 4
+          
+     def generate(self):
+          self.reg = [OperandFactory.create(self.mode).generate() 
+                      for i in range(self.numRegs)]
+          self.base = OperandFactory.create('x').generate()
+          return self
+
+     def astr(self):
+          address = ["[%s, #%s]", "[%s, #%s]!", "[%s], #%s"][self.kind]
+          address = address % (self.base.astr('x'), self.offset)
+          result = "%s\t%s, %s, %s" \
+              % (self.asmname, 
+                 self.reg[0].astr(self.asmRegPrefix), 
+                 self.reg[1].astr(self.asmRegPrefix), address)
+          return result
+
+     def cstr(self):
+          address = {
+               Address.base_plus_unscaled_offset: "Address(%s, %s)" \
+                    % (str(self.base), self.offset),
+               Address.pre: "Address(__ pre(%s, %s))" % (str(self.base), self.offset),
+               Address.post: "Address(__ post(%s, %s))" % (str(self.base), self.offset),
+               } [self.kind]
+          result = "__ %s(%s, %s, %s);" \
+              % (self.name(), self.reg[0], self.reg[1], address)
+          return result
+
+class FloatInstruction(Instruction):
+
+    def aname(self):
+        if (self._name.endswith("s") | self._name.endswith("d")):
+            return self._name[:len(self._name)-1]
+        else:
+            return self._name
+
+    def __init__(self, args):
+        name, self.modes = args
+        Instruction.__init__(self, name)
+
+    def generate(self):
+        self.reg = [OperandFactory.create(self.modes[i]).generate() 
+                    for i in range(self.numRegs)]
+        return self
+
+    def cstr(self):
+        formatStr = "%s%s" + ''.join([", %s" for i in range(1, self.numRegs)] + [");"])
+        return (formatStr
+                % tuple([Instruction.cstr(self)] +
+                        [str(self.reg[i]) for i in range(self.numRegs)])) # Yowza
+    
+    def astr(self):
+        formatStr = "%s%s" + ''.join([", %s" for i in range(1, self.numRegs)])
+        return (formatStr
+                % tuple([Instruction.astr(self)] +
+                        [(self.reg[i].astr(self.modes[i])) for i in range(self.numRegs)]))
+
+class LdStSIMDOp(Instruction):
+    def __init__(self, args):
+        self._name, self.regnum, self.arrangement, self.addresskind = args
+
+    def generate(self):
+        self.address = Address().generate(self.addresskind, 0)
+        self._firstSIMDreg = FloatRegister().generate()
+        if (self.addresskind  == Address.post):
+            if (self._name in ["ld1r", "ld2r", "ld3r", "ld4r"]):
+                elem_size = {"8B" : 1, "16B" : 1, "4H" : 2, "8H" : 2, "2S" : 4, "4S" : 4, "1D" : 8, "2D" : 8} [self.arrangement]
+                self.address.offset = self.regnum * elem_size
+            else:
+                if (self.arrangement in ["8B", "4H", "2S", "1D"]):
+                    self.address.offset = self.regnum * 8
+                else:
+                    self.address.offset = self.regnum * 16
+        return self
+
+    def cstr(self):
+        buf = super(LdStSIMDOp, self).cstr() + str(self._firstSIMDreg)
+        current = self._firstSIMDreg
+        for cnt in range(1, self.regnum):
+            buf = '%s, %s' % (buf, current.nextReg())
+            current = current.nextReg()
+        return '%s, __ T%s, %s);' % (buf, self.arrangement, str(self.address))
+
+    def astr(self):
+        buf = '%s\t{%s.%s' % (self._name, self._firstSIMDreg, self.arrangement)
+        current = self._firstSIMDreg
+        for cnt in range(1, self.regnum):
+            buf = '%s, %s.%s' % (buf, current.nextReg(), self.arrangement)
+            current = current.nextReg()
+        return  '%s}, %s' % (buf, self.address.astr("x"))
+
+    def aname(self):
+         return self._name
+
+class LSEOp(Instruction):
+    def __init__(self, args):
+        self._name, self.asmname, self.size, self.suffix = args
+
+    def generate(self):
+        self._name = "%s%s" % (self._name, self.suffix)
+        self.asmname = "%s%s" % (self.asmname, self.suffix)
+        self.srcReg = GeneralRegisterOrZr().generate()
+        self.tgtReg = GeneralRegisterOrZr().generate()
+        self.adrReg = GeneralRegisterOrSp().generate()
+
+        return self
+
+    def cstr(self):
+        sizeSpec = {"x" : "Assembler::xword", "w" : "Assembler::word"} [self.size]
+        return super(LSEOp, self).cstr() + "%s, %s, %s, %s);" % (sizeSpec, self.srcReg, self.tgtReg, self.adrReg)
+
+    def astr(self):
+        return "%s\t%s, %s, [%s]" % (self.asmname, self.srcReg.astr(self.size), self.tgtReg.astr(self.size), self.adrReg.astr("x"))
+
+    def aname(self):
+         return self.asmname
+
+class TwoRegFloatOp(FloatInstruction):
+    numRegs = 2
+
+class ThreeRegFloatOp(TwoRegFloatOp):
+    numRegs = 3
+
+class FourRegFloatOp(TwoRegFloatOp):
+    numRegs = 4
+
+class FloatConvertOp(TwoRegFloatOp):
+
+    def __init__(self, args):
+        self._cname, self._aname, modes = args
+        TwoRegFloatOp.__init__(self, [self._cname, modes])
+
+    def aname(self):
+        return self._aname
+
+    def cname(self):
+        return self._cname
+
+class SpecialCases(Instruction):
+    def __init__(self, data):
+        self._name = data[0]
+        self._cstr = data[1]
+        self._astr = data[2]
+
+    def cstr(self):
+        return self._cstr
+
+    def astr(self):
+        return self._astr
+
+def generate(kind, names):
+    outfile.write("# " + kind.__name__ + "\n");
+    print "\n// " + kind.__name__
+    for name in names:
+        for i in range(1):
+             op = kind(name).generate()
+             if op.multipleForms():
+                  forms = op.forms()
+                  aforms = op.aforms()
+                  for i in range(op.multipleForms()):
+                       cstr = op.cstr() % forms[i]
+                       astr = op.astr() % aforms[i]
+                       print "    %-50s //\t%s" % (cstr, astr)
+                       outfile.write("\t" + astr + "\n")
+             else:
+                  print "    %-50s //\t%s" % (op.cstr(), op.astr())
+                  outfile.write("\t" + op.astr() + "\n")
+
+outfile = open("aarch64ops.s", "w")
+
+print "// BEGIN  Generated code -- do not edit"
+print "// Generated by aarch64-asmtest.py"
+
+print "    Label back, forth;"
+print "    __ bind(back);"
+
+outfile.write("back:\n")
+
+generate (ArithOp, 
+          [ "add", "sub", "adds", "subs",
+            "addw", "subw", "addsw", "subsw",
+            "and", "orr", "eor", "ands",
+            "andw", "orrw", "eorw", "andsw", 
+            "bic", "orn", "eon", "bics", 
+            "bicw", "ornw", "eonw", "bicsw" ])
+
+generate (AddSubImmOp, 
+          [ "addw", "addsw", "subw", "subsw",
+            "add", "adds", "sub", "subs"])
+generate (LogicalImmOp, 
+          [ "andw", "orrw", "eorw", "andsw",
+            "and", "orr", "eor", "ands"])
+
+generate (AbsOp, [ "b", "bl" ])
+
+generate (RegAndAbsOp, ["cbzw", "cbnzw", "cbz", "cbnz", "adr", "adrp"])
+
+generate (RegImmAbsOp, ["tbz", "tbnz"])
+
+generate (MoveWideImmOp, ["movnw", "movzw", "movkw", "movn", "movz", "movk"])
+
+generate (BitfieldOp, ["sbfm", "bfmw", "ubfmw", "sbfm", "bfm", "ubfm"])
+
+generate (ExtractOp, ["extrw", "extr"])
+
+generate (CondBranchOp, ["EQ", "NE", "HS", "CS", "LO", "CC", "MI", "PL", "VS", "VC",
+                        "HI", "LS", "GE", "LT", "GT", "LE", "AL", "NV" ])
+
+generate (ImmOp, ["svc", "hvc", "smc", "brk", "hlt", # "dpcs1",  "dpcs2",  "dpcs3"
+               ])
+
+generate (Op, ["nop", "eret", "drps", "isb"])
+
+barriers = ["OSHLD", "OSHST", "OSH", "NSHLD", "NSHST", "NSH",
+            "ISHLD", "ISHST", "ISH", "LD", "ST", "SY"]
+
+generate (SystemOp, [["dsb", barriers], ["dmb", barriers]])
+
+generate (OneRegOp, ["br", "blr"])
+
+for mode in 'xwhb':
+    generate (LoadStoreExclusiveOp, [["stxr", mode, 3], ["stlxr", mode, 3],
+                                     ["ldxr", mode, 2], ["ldaxr", mode, 2],
+                                     ["stlr", mode, 2], ["ldar", mode, 2]])
+
+for mode in 'xw':
+    generate (LoadStoreExclusiveOp, [["ldxp", mode, 3], ["ldaxp", mode, 3],
+                                     ["stxp", mode, 4], ["stlxp", mode, 4]])
+
+for kind in range(6):
+    print "\n// " + Address.kindToStr(kind),
+    if kind != Address.pcrel:
+        generate (LoadStoreOp, 
+                  [["str", "str", kind, "x"], ["str", "str", kind, "w"], 
+                   ["str", "strb", kind, "b"], ["str", "strh", kind, "h"],
+                   ["ldr", "ldr", kind, "x"], ["ldr", "ldr", kind, "w"], 
+                   ["ldr", "ldrb", kind, "b"], ["ldr", "ldrh", kind, "h"],
+                   ["ldrsb", "ldrsb", kind, "x"], ["ldrsh", "ldrsh", kind, "x"], 
+                   ["ldrsh", "ldrsh", kind, "w"], ["ldrsw", "ldrsw", kind, "x"],
+                   ["ldr", "ldr", kind, "d"], ["ldr", "ldr", kind, "s"], 
+                   ["str", "str", kind, "d"], ["str", "str", kind, "s"], 
+                   ])
+    else:
+        generate (LoadStoreOp, 
+                  [["ldr", "ldr", kind, "x"], ["ldr", "ldr", kind, "w"]])
+        
+
+for kind in (Address.base_plus_unscaled_offset, Address.pcrel, Address.base_plus_reg, \
+                 Address.base_plus_scaled_offset):
+    generate (LoadStoreOp, 
+              [["prfm", "prfm\tPLDL1KEEP,", kind, "x"]])
+
+generate(AddSubCarryOp, ["adcw", "adcsw", "sbcw", "sbcsw", "adc", "adcs", "sbc", "sbcs"])
+
+generate(AddSubExtendedOp, ["addw", "addsw", "sub", "subsw", "add", "adds", "sub", "subs"])
+
+generate(ConditionalCompareOp, ["ccmnw", "ccmpw", "ccmn", "ccmp"])
+generate(ConditionalCompareImmedOp, ["ccmnw", "ccmpw", "ccmn", "ccmp"])
+generate(ConditionalSelectOp, 
+         ["cselw", "csincw", "csinvw", "csnegw", "csel", "csinc", "csinv", "csneg"])
+
+generate(TwoRegOp, 
+         ["rbitw", "rev16w", "revw", "clzw", "clsw", "rbit", 
+          "rev16", "rev32", "rev", "clz", "cls"])
+generate(ThreeRegOp, 
+         ["udivw", "sdivw", "lslvw", "lsrvw", "asrvw", "rorvw", "udiv", "sdiv", 
+          "lslv", "lsrv", "asrv", "rorv", "umulh", "smulh"])
+generate(FourRegMulOp, 
+         ["maddw", "msubw", "madd", "msub", "smaddl", "smsubl", "umaddl", "umsubl"])
+
+generate(ThreeRegFloatOp, 
+         [["fmuls", "sss"], ["fdivs", "sss"], ["fadds", "sss"], ["fsubs", "sss"], 
+          ["fmuls", "sss"],
+          ["fmuld", "ddd"], ["fdivd", "ddd"], ["faddd", "ddd"], ["fsubd", "ddd"], 
+          ["fmuld", "ddd"]])
+
+generate(FourRegFloatOp, 
+         [["fmadds", "ssss"], ["fmsubs", "ssss"], ["fnmadds", "ssss"], ["fnmadds", "ssss"], 
+          ["fmaddd", "dddd"], ["fmsubd", "dddd"], ["fnmaddd", "dddd"], ["fnmaddd", "dddd"],])
+
+generate(TwoRegFloatOp, 
+         [["fmovs", "ss"], ["fabss", "ss"], ["fnegs", "ss"], ["fsqrts", "ss"], 
+          ["fcvts", "ds"],
+          ["fmovd", "dd"], ["fabsd", "dd"], ["fnegd", "dd"], ["fsqrtd", "dd"], 
+          ["fcvtd", "sd"],
+          ])
+
+generate(FloatConvertOp, [["fcvtzsw", "fcvtzs", "ws"], ["fcvtzs", "fcvtzs", "xs"],
+                          ["fcvtzdw", "fcvtzs", "wd"], ["fcvtzd", "fcvtzs", "xd"],
+                          ["scvtfws", "scvtf", "sw"], ["scvtfs", "scvtf", "sx"],
+                          ["scvtfwd", "scvtf", "dw"], ["scvtfd", "scvtf", "dx"],
+                          ["fmovs", "fmov", "ws"], ["fmovd", "fmov", "xd"],
+                          ["fmovs", "fmov", "sw"], ["fmovd", "fmov", "dx"]])
+
+generate(TwoRegFloatOp, [["fcmps", "ss"], ["fcmpd", "dd"], 
+                         ["fcmps", "sz"], ["fcmpd", "dz"]])
+
+for kind in range(3):
+     generate(LoadStorePairOp, [["stp", "stp", kind, "w"], ["ldp", "ldp", kind, "w"],
+                                ["ldpsw", "ldpsw", kind, "x"], 
+                                ["stp", "stp", kind, "x"], ["ldp", "ldp", kind, "x"]
+                                ])
+generate(LoadStorePairOp, [["stnp", "stnp", 0, "w"], ["ldnp", "ldnp", 0, "w"],
+                           ["stnp", "stnp", 0, "x"], ["ldnp", "ldnp", 0, "x"]])
+
+generate(LdStSIMDOp, [["ld1",  1, "8B",  Address.base_only],
+                      ["ld1",  2, "16B", Address.post],
+                      ["ld1",  3, "1D",  Address.post_reg],
+                      ["ld1",  4, "8H",  Address.post],
+                      ["ld1r", 1, "8B",  Address.base_only],
+                      ["ld1r", 1, "4S",  Address.post],
+                      ["ld1r", 1, "1D",  Address.post_reg],
+                      ["ld2",  2, "2D",  Address.base_only],
+                      ["ld2",  2, "4H",  Address.post],
+                      ["ld2r", 2, "16B", Address.base_only],
+                      ["ld2r", 2, "2S",  Address.post],
+                      ["ld2r", 2, "2D",  Address.post_reg],
+                      ["ld3",  3, "4S",  Address.post_reg],
+                      ["ld3",  3, "2S",  Address.base_only],
+                      ["ld3r", 3, "8H",  Address.base_only],
+                      ["ld3r", 3, "4S",  Address.post],
+                      ["ld3r", 3, "1D",  Address.post_reg],
+                      ["ld4",  4, "8H",  Address.post],
+                      ["ld4",  4, "8B",  Address.post_reg],
+                      ["ld4r", 4, "8B",  Address.base_only],
+                      ["ld4r", 4, "4H",  Address.post],
+                      ["ld4r", 4, "2S",  Address.post_reg],
+])
+
+generate(SpecialCases, [["ccmn",   "__ ccmn(zr, zr, 3u, Assembler::LE);",                "ccmn\txzr, xzr, #3, LE"],
+                        ["ccmnw",  "__ ccmnw(zr, zr, 5u, Assembler::EQ);",               "ccmn\twzr, wzr, #5, EQ"],
+                        ["ccmp",   "__ ccmp(zr, 1, 4u, Assembler::NE);",                 "ccmp\txzr, 1, #4, NE"],
+                        ["ccmpw",  "__ ccmpw(zr, 2, 2, Assembler::GT);",                 "ccmp\twzr, 2, #2, GT"],
+                        ["extr",   "__ extr(zr, zr, zr, 0);",                            "extr\txzr, xzr, xzr, 0"],
+                        ["stlxp",  "__ stlxp(r0, zr, zr, sp);",                          "stlxp\tw0, xzr, xzr, [sp]"],
+                        ["stlxpw", "__ stlxpw(r2, zr, zr, r3);",                         "stlxp\tw2, wzr, wzr, [x3]"],
+                        ["stxp",   "__ stxp(r4, zr, zr, r5);",                           "stxp\tw4, xzr, xzr, [x5]"],
+                        ["stxpw",  "__ stxpw(r6, zr, zr, sp);",                          "stxp\tw6, wzr, wzr, [sp]"],
+                        ["dup",    "__ dup(v0, __ T16B, zr);",                           "dup\tv0.16b, wzr"],
+                        ["mov",    "__ mov(v1, __ T1D, 0, zr);",                         "mov\tv1.d[0], xzr"],
+                        ["mov",    "__ mov(v1, __ T2S, 1, zr);",                         "mov\tv1.s[1], wzr"],
+                        ["mov",    "__ mov(v1, __ T4H, 2, zr);",                         "mov\tv1.h[2], wzr"],
+                        ["mov",    "__ mov(v1, __ T8B, 3, zr);",                         "mov\tv1.b[3], wzr"],
+                        ["ld1",    "__ ld1(v31, v0, __ T2D, Address(__ post(r1, r0)));", "ld1\t{v31.2d, v0.2d}, [x1], x0"]])
+
+print "\n// FloatImmediateOp"
+for float in ("2.0", "2.125", "4.0", "4.25", "8.0", "8.5", "16.0", "17.0", "0.125", 
+              "0.1328125", "0.25", "0.265625", "0.5", "0.53125", "1.0", "1.0625", 
+              "-2.0", "-2.125", "-4.0", "-4.25", "-8.0", "-8.5", "-16.0", "-17.0", 
+              "-0.125", "-0.1328125", "-0.25", "-0.265625", "-0.5", "-0.53125", "-1.0", "-1.0625"):
+    astr = "fmov d0, #" + float
+    cstr = "__ fmovd(v0, " + float + ");"
+    print "    %-50s //\t%s" % (cstr, astr)
+    outfile.write("\t" + astr + "\n")
+
+# ARMv8.1A
+for size in ("x", "w"):
+    for suffix in ("", "a", "al", "l"):
+        generate(LSEOp, [["swp", "swp", size, suffix],
+                         ["ldadd", "ldadd", size, suffix],
+                         ["ldbic", "ldclr", size, suffix],
+                         ["ldeor", "ldeor", size, suffix],
+                         ["ldorr", "ldset", size, suffix],
+                         ["ldsmin", "ldsmin", size, suffix],
+                         ["ldsmax", "ldsmax", size, suffix],
+                         ["ldumin", "ldumin", size, suffix],
+                         ["ldumax", "ldumax", size, suffix]]);
+
+print "\n    __ bind(forth);"
+outfile.write("forth:\n")
+
+outfile.close()
+
+import subprocess
+import sys
+
+# compile for 8.1 because of lse atomics
+subprocess.check_call([AARCH64_AS, "-march=armv8.1-a", "aarch64ops.s", "-o", "aarch64ops.o"])
+
+print
+print "/*",
+sys.stdout.flush()
+subprocess.check_call([AARCH64_OBJDUMP, "-d", "aarch64ops.o"])
+print "*/"
+
+subprocess.check_call([AARCH64_OBJCOPY, "-O", "binary", "-j", ".text", "aarch64ops.o", "aarch64ops.bin"])
+
+infile = open("aarch64ops.bin", "r")
+bytes = bytearray(infile.read())
+
+print
+print "  static const unsigned int insns[] ="
+print "  {"
+
+i = 0
+while i < len(bytes):
+     print "    0x%02x%02x%02x%02x," % (bytes[i+3], bytes[i+2], bytes[i+1], bytes[i]),
+     i += 4
+     if i%16 == 0:
+          print
+print "\n  };"
+print "// END  Generated code -- do not edit"
+
+
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -103,531 +103,662 @@
     __ bind(back);
 
 // ArithOp
-    __ add(r19, r22, r7, Assembler::LSL, 28);          //       add     x19, x22, x7, LSL #28
-    __ sub(r16, r11, r10, Assembler::LSR, 13);         //       sub     x16, x11, x10, LSR #13
-    __ adds(r27, r13, r28, Assembler::ASR, 2);         //       adds    x27, x13, x28, ASR #2
-    __ subs(r20, r28, r26, Assembler::ASR, 41);        //       subs    x20, x28, x26, ASR #41
-    __ addw(r8, r19, r19, Assembler::ASR, 19);         //       add     w8, w19, w19, ASR #19
-    __ subw(r4, r9, r10, Assembler::LSL, 14);          //       sub     w4, w9, w10, LSL #14
-    __ addsw(r8, r11, r30, Assembler::LSL, 13);        //       adds    w8, w11, w30, LSL #13
-    __ subsw(r0, r25, r19, Assembler::LSL, 9);         //       subs    w0, w25, w19, LSL #9
-    __ andr(r20, r0, r21, Assembler::LSL, 19);         //       and     x20, x0, x21, LSL #19
-    __ orr(r21, r14, r20, Assembler::LSL, 17);         //       orr     x21, x14, x20, LSL #17
-    __ eor(r25, r28, r1, Assembler::LSL, 51);          //       eor     x25, x28, x1, LSL #51
-    __ ands(r10, r27, r11, Assembler::ASR, 15);        //       ands    x10, x27, x11, ASR #15
-    __ andw(r25, r5, r12, Assembler::ASR, 23);         //       and     w25, w5, w12, ASR #23
-    __ orrw(r18, r14, r10, Assembler::LSR, 4);         //       orr     w18, w14, w10, LSR #4
-    __ eorw(r4, r21, r5, Assembler::ASR, 22);          //       eor     w4, w21, w5, ASR #22
-    __ andsw(r21, r0, r5, Assembler::ASR, 29);         //       ands    w21, w0, w5, ASR #29
-    __ bic(r26, r30, r6, Assembler::ASR, 37);          //       bic     x26, x30, x6, ASR #37
-    __ orn(r3, r1, r13, Assembler::LSR, 29);           //       orn     x3, x1, x13, LSR #29
-    __ eon(r0, r28, r9, Assembler::LSL, 47);           //       eon     x0, x28, x9, LSL #47
-    __ bics(r29, r5, r28, Assembler::LSL, 46);         //       bics    x29, x5, x28, LSL #46
-    __ bicw(r9, r18, r7, Assembler::LSR, 20);          //       bic     w9, w18, w7, LSR #20
-    __ ornw(r26, r13, r25, Assembler::ASR, 24);        //       orn     w26, w13, w25, ASR #24
-    __ eonw(r25, r4, r19, Assembler::LSL, 6);          //       eon     w25, w4, w19, LSL #6
-    __ bicsw(r5, r26, r4, Assembler::LSR, 24);         //       bics    w5, w26, w4, LSR #24
+    __ add(r15, r12, r16, Assembler::LSR, 30);         //        add        x15, x12, x16, LSR #30
+    __ sub(r1, r15, r3, Assembler::LSR, 32);           //        sub        x1, x15, x3, LSR #32
+    __ adds(r13, r25, r5, Assembler::LSL, 13);         //        adds        x13, x25, x5, LSL #13
+    __ subs(r22, r28, r6, Assembler::ASR, 17);         //        subs        x22, x28, x6, ASR #17
+    __ addw(r0, r9, r22, Assembler::ASR, 6);           //        add        w0, w9, w22, ASR #6
+    __ subw(r19, r3, r25, Assembler::LSL, 21);         //        sub        w19, w3, w25, LSL #21
+    __ addsw(r4, r19, r11, Assembler::LSL, 20);        //        adds        w4, w19, w11, LSL #20
+    __ subsw(r24, r7, r19, Assembler::ASR, 0);         //        subs        w24, w7, w19, ASR #0
+    __ andr(r30, r7, r11, Assembler::LSL, 48);         //        and        x30, x7, x11, LSL #48
+    __ orr(r24, r8, r15, Assembler::LSL, 12);          //        orr        x24, x8, x15, LSL #12
+    __ eor(r17, r9, r23, Assembler::LSL, 1);           //        eor        x17, x9, x23, LSL #1
+    __ ands(r14, r11, r4, Assembler::LSR, 55);         //        ands        x14, x11, x4, LSR #55
+    __ andw(r19, r7, r12, Assembler::LSR, 17);         //        and        w19, w7, w12, LSR #17
+    __ orrw(r19, r27, r11, Assembler::ASR, 28);        //        orr        w19, w27, w11, ASR #28
+    __ eorw(r30, r3, r22, Assembler::LSR, 31);         //        eor        w30, w3, w22, LSR #31
+    __ andsw(r19, r26, r28, Assembler::ASR, 0);        //        ands        w19, w26, w28, ASR #0
+    __ bic(r29, r6, r26, Assembler::LSL, 51);          //        bic        x29, x6, x26, LSL #51
+    __ orn(r26, r27, r17, Assembler::LSL, 35);         //        orn        x26, x27, x17, LSL #35
+    __ eon(r21, r4, r14, Assembler::LSL, 5);           //        eon        x21, x4, x14, LSL #5
+    __ bics(r2, r15, r0, Assembler::ASR, 5);           //        bics        x2, x15, x0, ASR #5
+    __ bicw(r2, r7, r2, Assembler::LSL, 29);           //        bic        w2, w7, w2, LSL #29
+    __ ornw(r24, r12, r21, Assembler::LSR, 5);         //        orn        w24, w12, w21, LSR #5
+    __ eonw(r30, r15, r19, Assembler::LSL, 2);         //        eon        w30, w15, w19, LSL #2
+    __ bicsw(r30, r23, r17, Assembler::ASR, 28);       //        bics        w30, w23, w17, ASR #28
 
 // AddSubImmOp
-    __ addw(r7, r19, 340u);                            //       add     w7, w19, #340
-    __ addsw(r8, r0, 401u);                            //       adds    w8, w0, #401
-    __ subw(r29, r20, 163u);                           //       sub     w29, w20, #163
-    __ subsw(r8, r23, 759u);                           //       subs    w8, w23, #759
-    __ add(r1, r12, 523u);                             //       add     x1, x12, #523
-    __ adds(r2, r11, 426u);                            //       adds    x2, x11, #426
-    __ sub(r14, r29, 716u);                            //       sub     x14, x29, #716
-    __ subs(r11, r5, 582u);                            //       subs    x11, x5, #582
+    __ addw(r4, r20, 660u);                            //        add        w4, w20, #660
+    __ addsw(r2, r10, 710u);                           //        adds        w2, w10, #710
+    __ subw(r19, r26, 244u);                           //        sub        w19, w26, #244
+    __ subsw(r28, r13, 73u);                           //        subs        w28, w13, #73
+    __ add(r2, r30, 862u);                             //        add        x2, x30, #862
+    __ adds(r27, r16, 574u);                           //        adds        x27, x16, #574
+    __ sub(r22, r9, 589u);                             //        sub        x22, x9, #589
+    __ subs(r4, r1, 698u);                             //        subs        x4, x1, #698
 
 // LogicalImmOp
-    __ andw(r23, r22, 32768ul);                        //       and     w23, w22, #0x8000
-    __ orrw(r4, r10, 4042322160ul);                    //       orr     w4, w10, #0xf0f0f0f0
-    __ eorw(r0, r24, 4042322160ul);                    //       eor     w0, w24, #0xf0f0f0f0
-    __ andsw(r19, r29, 2139127680ul);                  //       ands    w19, w29, #0x7f807f80
-    __ andr(r5, r10, 4503599627354112ul);              //       and     x5, x10, #0xfffffffffc000
-    __ orr(r12, r30, 18445618178097414144ul);          //       orr     x12, x30, #0xfffc0000fffc0000
-    __ eor(r30, r5, 262128ul);                         //       eor     x30, x5, #0x3fff0
-    __ ands(r26, r23, 4194300ul);                      //       ands    x26, x23, #0x3ffffc
+    __ andw(r28, r19, 4294709247ul);                   //        and        w28, w19, #0xfffc0fff
+    __ orrw(r27, r5, 536870910ul);                     //        orr        w27, w5, #0x1ffffffe
+    __ eorw(r30, r20, 4294840319ul);                   //        eor        w30, w20, #0xfffe0fff
+    __ andsw(r22, r26, 4294959615ul);                  //        ands        w22, w26, #0xffffe1ff
+    __ andr(r5, r7, 4194300ul);                        //        and        x5, x7, #0x3ffffc
+    __ orr(r13, r7, 18014398509481728ul);              //        orr        x13, x7, #0x3fffffffffff00
+    __ eor(r7, r9, 18442240474082197503ul);            //        eor        x7, x9, #0xfff0000000003fff
+    __ ands(r3, r0, 18374686479671656447ul);           //        ands        x3, x0, #0xff00000000007fff
 
 // AbsOp
-    __ b(__ pc());                                     //       b       .
-    __ b(back);                                        //       b       back
-    __ b(forth);                                       //       b       forth
-    __ bl(__ pc());                                    //       bl      .
-    __ bl(back);                                       //       bl      back
-    __ bl(forth);                                      //       bl      forth
+    __ b(__ pc());                                     //        b        .
+    __ b(back);                                        //        b        back
+    __ b(forth);                                       //        b        forth
+    __ bl(__ pc());                                    //        bl        .
+    __ bl(back);                                       //        bl        back
+    __ bl(forth);                                      //        bl        forth
 
 // RegAndAbsOp
-    __ cbzw(r12, __ pc());                             //       cbz     w12, .
-    __ cbzw(r12, back);                                //       cbz     w12, back
-    __ cbzw(r12, forth);                               //       cbz     w12, forth
-    __ cbnzw(r20, __ pc());                            //       cbnz    w20, .
-    __ cbnzw(r20, back);                               //       cbnz    w20, back
-    __ cbnzw(r20, forth);                              //       cbnz    w20, forth
-    __ cbz(r12, __ pc());                              //       cbz     x12, .
-    __ cbz(r12, back);                                 //       cbz     x12, back
-    __ cbz(r12, forth);                                //       cbz     x12, forth
-    __ cbnz(r24, __ pc());                             //       cbnz    x24, .
-    __ cbnz(r24, back);                                //       cbnz    x24, back
-    __ cbnz(r24, forth);                               //       cbnz    x24, forth
-    __ adr(r6, __ pc());                               //       adr     x6, .
-    __ adr(r6, back);                                  //       adr     x6, back
-    __ adr(r6, forth);                                 //       adr     x6, forth
-    __ _adrp(r21, __ pc());                             //      adrp    x21, .
+    __ cbzw(r16, __ pc());                             //        cbz        w16, .
+    __ cbzw(r16, back);                                //        cbz        w16, back
+    __ cbzw(r16, forth);                               //        cbz        w16, forth
+    __ cbnzw(r19, __ pc());                            //        cbnz        w19, .
+    __ cbnzw(r19, back);                               //        cbnz        w19, back
+    __ cbnzw(r19, forth);                              //        cbnz        w19, forth
+    __ cbz(r5, __ pc());                               //        cbz        x5, .
+    __ cbz(r5, back);                                  //        cbz        x5, back
+    __ cbz(r5, forth);                                 //        cbz        x5, forth
+    __ cbnz(r4, __ pc());                              //        cbnz        x4, .
+    __ cbnz(r4, back);                                 //        cbnz        x4, back
+    __ cbnz(r4, forth);                                //        cbnz        x4, forth
+    __ adr(r27, __ pc());                              //        adr        x27, .
+    __ adr(r27, back);                                 //        adr        x27, back
+    __ adr(r27, forth);                                //        adr        x27, forth
+    __ _adrp(r16, __ pc());                            //        adrp        x16, .
 
 // RegImmAbsOp
-    __ tbz(r1, 1, __ pc());                            //       tbz     x1, #1, .
-    __ tbz(r1, 1, back);                               //       tbz     x1, #1, back
-    __ tbz(r1, 1, forth);                              //       tbz     x1, #1, forth
-    __ tbnz(r8, 9, __ pc());                           //       tbnz    x8, #9, .
-    __ tbnz(r8, 9, back);                              //       tbnz    x8, #9, back
-    __ tbnz(r8, 9, forth);                             //       tbnz    x8, #9, forth
+    __ tbz(r28, 8, __ pc());                           //        tbz        x28, #8, .
+    __ tbz(r28, 8, back);                              //        tbz        x28, #8, back
+    __ tbz(r28, 8, forth);                             //        tbz        x28, #8, forth
+    __ tbnz(r1, 1, __ pc());                           //        tbnz        x1, #1, .
+    __ tbnz(r1, 1, back);                              //        tbnz        x1, #1, back
+    __ tbnz(r1, 1, forth);                             //        tbnz        x1, #1, forth
 
 // MoveWideImmOp
-    __ movnw(r12, 23175, 0);                           //       movn    w12, #23175, lsl 0
-    __ movzw(r11, 20476, 16);                          //       movz    w11, #20476, lsl 16
-    __ movkw(r21, 3716, 0);                            //       movk    w21, #3716, lsl 0
-    __ movn(r29, 28661, 48);                           //       movn    x29, #28661, lsl 48
-    __ movz(r3, 6927, 0);                              //       movz    x3, #6927, lsl 0
-    __ movk(r22, 9828, 16);                            //       movk    x22, #9828, lsl 16
+    __ movnw(r20, 8639, 16);                           //        movn        w20, #8639, lsl 16
+    __ movzw(r7, 25835, 0);                            //        movz        w7, #25835, lsl 0
+    __ movkw(r17, 7261, 0);                            //        movk        w17, #7261, lsl 0
+    __ movn(r14, 2097, 32);                            //        movn        x14, #2097, lsl 32
+    __ movz(r9, 16082, 0);                             //        movz        x9, #16082, lsl 0
+    __ movk(r19, 13962, 16);                           //        movk        x19, #13962, lsl 16
 
 // BitfieldOp
-    __ sbfm(r12, r8, 6, 22);                           //       sbfm    x12, x8, #6, #22
-    __ bfmw(r19, r25, 25, 19);                         //       bfm     w19, w25, #25, #19
-    __ ubfmw(r9, r12, 29, 15);                         //       ubfm    w9, w12, #29, #15
-    __ sbfm(r28, r25, 16, 16);                         //       sbfm    x28, x25, #16, #16
-    __ bfm(r12, r5, 4, 25);                            //       bfm     x12, x5, #4, #25
-    __ ubfm(r0, r10, 6, 8);                            //       ubfm    x0, x10, #6, #8
+    __ sbfm(r9, r22, 6, 22);                           //        sbfm        x9, x22, #6, #22
+    __ bfmw(r19, r0, 11, 0);                           //        bfm        w19, w0, #11, #0
+    __ ubfmw(r10, r19, 11, 19);                        //        ubfm        w10, w19, #11, #19
+    __ sbfm(r4, r15, 5, 17);                           //        sbfm        x4, x15, #5, #17
+    __ bfm(r3, r5, 19, 28);                            //        bfm        x3, x5, #19, #28
+    __ ubfm(r12, r28, 17, 2);                          //        ubfm        x12, x28, #17, #2
 
 // ExtractOp
-    __ extrw(r4, r13, r26, 24);                        //       extr    w4, w13, w26, #24
-    __ extr(r23, r30, r24, 31);                        //       extr    x23, x30, x24, #31
+    __ extrw(r15, r0, r22, 3);                         //        extr        w15, w0, w22, #3
+    __ extr(r6, r14, r14, 55);                         //        extr        x6, x14, x14, #55
 
 // CondBranchOp
-    __ br(Assembler::EQ, __ pc());                     //       b.EQ    .
-    __ br(Assembler::EQ, back);                        //       b.EQ    back
-    __ br(Assembler::EQ, forth);                       //       b.EQ    forth
-    __ br(Assembler::NE, __ pc());                     //       b.NE    .
-    __ br(Assembler::NE, back);                        //       b.NE    back
-    __ br(Assembler::NE, forth);                       //       b.NE    forth
-    __ br(Assembler::HS, __ pc());                     //       b.HS    .
-    __ br(Assembler::HS, back);                        //       b.HS    back
-    __ br(Assembler::HS, forth);                       //       b.HS    forth
-    __ br(Assembler::CS, __ pc());                     //       b.CS    .
-    __ br(Assembler::CS, back);                        //       b.CS    back
-    __ br(Assembler::CS, forth);                       //       b.CS    forth
-    __ br(Assembler::LO, __ pc());                     //       b.LO    .
-    __ br(Assembler::LO, back);                        //       b.LO    back
-    __ br(Assembler::LO, forth);                       //       b.LO    forth
-    __ br(Assembler::CC, __ pc());                     //       b.CC    .
-    __ br(Assembler::CC, back);                        //       b.CC    back
-    __ br(Assembler::CC, forth);                       //       b.CC    forth
-    __ br(Assembler::MI, __ pc());                     //       b.MI    .
-    __ br(Assembler::MI, back);                        //       b.MI    back
-    __ br(Assembler::MI, forth);                       //       b.MI    forth
-    __ br(Assembler::PL, __ pc());                     //       b.PL    .
-    __ br(Assembler::PL, back);                        //       b.PL    back
-    __ br(Assembler::PL, forth);                       //       b.PL    forth
-    __ br(Assembler::VS, __ pc());                     //       b.VS    .
-    __ br(Assembler::VS, back);                        //       b.VS    back
-    __ br(Assembler::VS, forth);                       //       b.VS    forth
-    __ br(Assembler::VC, __ pc());                     //       b.VC    .
-    __ br(Assembler::VC, back);                        //       b.VC    back
-    __ br(Assembler::VC, forth);                       //       b.VC    forth
-    __ br(Assembler::HI, __ pc());                     //       b.HI    .
-    __ br(Assembler::HI, back);                        //       b.HI    back
-    __ br(Assembler::HI, forth);                       //       b.HI    forth
-    __ br(Assembler::LS, __ pc());                     //       b.LS    .
-    __ br(Assembler::LS, back);                        //       b.LS    back
-    __ br(Assembler::LS, forth);                       //       b.LS    forth
-    __ br(Assembler::GE, __ pc());                     //       b.GE    .
-    __ br(Assembler::GE, back);                        //       b.GE    back
-    __ br(Assembler::GE, forth);                       //       b.GE    forth
-    __ br(Assembler::LT, __ pc());                     //       b.LT    .
-    __ br(Assembler::LT, back);                        //       b.LT    back
-    __ br(Assembler::LT, forth);                       //       b.LT    forth
-    __ br(Assembler::GT, __ pc());                     //       b.GT    .
-    __ br(Assembler::GT, back);                        //       b.GT    back
-    __ br(Assembler::GT, forth);                       //       b.GT    forth
-    __ br(Assembler::LE, __ pc());                     //       b.LE    .
-    __ br(Assembler::LE, back);                        //       b.LE    back
-    __ br(Assembler::LE, forth);                       //       b.LE    forth
-    __ br(Assembler::AL, __ pc());                     //       b.AL    .
-    __ br(Assembler::AL, back);                        //       b.AL    back
-    __ br(Assembler::AL, forth);                       //       b.AL    forth
-    __ br(Assembler::NV, __ pc());                     //       b.NV    .
-    __ br(Assembler::NV, back);                        //       b.NV    back
-    __ br(Assembler::NV, forth);                       //       b.NV    forth
+    __ br(Assembler::EQ, __ pc());                     //        b.EQ        .
+    __ br(Assembler::EQ, back);                        //        b.EQ        back
+    __ br(Assembler::EQ, forth);                       //        b.EQ        forth
+    __ br(Assembler::NE, __ pc());                     //        b.NE        .
+    __ br(Assembler::NE, back);                        //        b.NE        back
+    __ br(Assembler::NE, forth);                       //        b.NE        forth
+    __ br(Assembler::HS, __ pc());                     //        b.HS        .
+    __ br(Assembler::HS, back);                        //        b.HS        back
+    __ br(Assembler::HS, forth);                       //        b.HS        forth
+    __ br(Assembler::CS, __ pc());                     //        b.CS        .
+    __ br(Assembler::CS, back);                        //        b.CS        back
+    __ br(Assembler::CS, forth);                       //        b.CS        forth
+    __ br(Assembler::LO, __ pc());                     //        b.LO        .
+    __ br(Assembler::LO, back);                        //        b.LO        back
+    __ br(Assembler::LO, forth);                       //        b.LO        forth
+    __ br(Assembler::CC, __ pc());                     //        b.CC        .
+    __ br(Assembler::CC, back);                        //        b.CC        back
+    __ br(Assembler::CC, forth);                       //        b.CC        forth
+    __ br(Assembler::MI, __ pc());                     //        b.MI        .
+    __ br(Assembler::MI, back);                        //        b.MI        back
+    __ br(Assembler::MI, forth);                       //        b.MI        forth
+    __ br(Assembler::PL, __ pc());                     //        b.PL        .
+    __ br(Assembler::PL, back);                        //        b.PL        back
+    __ br(Assembler::PL, forth);                       //        b.PL        forth
+    __ br(Assembler::VS, __ pc());                     //        b.VS        .
+    __ br(Assembler::VS, back);                        //        b.VS        back
+    __ br(Assembler::VS, forth);                       //        b.VS        forth
+    __ br(Assembler::VC, __ pc());                     //        b.VC        .
+    __ br(Assembler::VC, back);                        //        b.VC        back
+    __ br(Assembler::VC, forth);                       //        b.VC        forth
+    __ br(Assembler::HI, __ pc());                     //        b.HI        .
+    __ br(Assembler::HI, back);                        //        b.HI        back
+    __ br(Assembler::HI, forth);                       //        b.HI        forth
+    __ br(Assembler::LS, __ pc());                     //        b.LS        .
+    __ br(Assembler::LS, back);                        //        b.LS        back
+    __ br(Assembler::LS, forth);                       //        b.LS        forth
+    __ br(Assembler::GE, __ pc());                     //        b.GE        .
+    __ br(Assembler::GE, back);                        //        b.GE        back
+    __ br(Assembler::GE, forth);                       //        b.GE        forth
+    __ br(Assembler::LT, __ pc());                     //        b.LT        .
+    __ br(Assembler::LT, back);                        //        b.LT        back
+    __ br(Assembler::LT, forth);                       //        b.LT        forth
+    __ br(Assembler::GT, __ pc());                     //        b.GT        .
+    __ br(Assembler::GT, back);                        //        b.GT        back
+    __ br(Assembler::GT, forth);                       //        b.GT        forth
+    __ br(Assembler::LE, __ pc());                     //        b.LE        .
+    __ br(Assembler::LE, back);                        //        b.LE        back
+    __ br(Assembler::LE, forth);                       //        b.LE        forth
+    __ br(Assembler::AL, __ pc());                     //        b.AL        .
+    __ br(Assembler::AL, back);                        //        b.AL        back
+    __ br(Assembler::AL, forth);                       //        b.AL        forth
+    __ br(Assembler::NV, __ pc());                     //        b.NV        .
+    __ br(Assembler::NV, back);                        //        b.NV        back
+    __ br(Assembler::NV, forth);                       //        b.NV        forth
 
 // ImmOp
-    __ svc(12729);                                     //       svc     #12729
-    __ hvc(6788);                                      //       hvc     #6788
-    __ smc(1535);                                      //       smc     #1535
-    __ brk(16766);                                     //       brk     #16766
-    __ hlt(9753);                                      //       hlt     #9753
+    __ svc(22064);                                     //        svc        #22064
+    __ hvc(533);                                       //        hvc        #533
+    __ smc(9942);                                      //        smc        #9942
+    __ brk(4714);                                      //        brk        #4714
+    __ hlt(4302);                                      //        hlt        #4302
 
 // Op
-    __ nop();                                          //       nop
-    __ eret();                                         //       eret
-    __ drps();                                         //       drps
-    __ isb();                                          //       isb
+    __ nop();                                          //        nop
+    __ eret();                                         //        eret
+    __ drps();                                         //        drps
+    __ isb();                                          //        isb
 
 // SystemOp
-    __ dsb(Assembler::SY);                             //       dsb     SY
-    __ dmb(Assembler::ISHST);                          //       dmb     ISHST
+    __ dsb(Assembler::OSH);                            //        dsb        OSH
+    __ dmb(Assembler::NSHLD);                          //        dmb        NSHLD
 
 // OneRegOp
-    __ br(r2);                                         //       br      x2
-    __ blr(r5);                                        //       blr     x5
+    __ br(r20);                                        //        br        x20
+    __ blr(r2);                                        //        blr        x2
 
 // LoadStoreExclusiveOp
-    __ stxr(r20, r21, r2);                             //       stxr    w20, x21, [x2]
-    __ stlxr(r5, r29, r7);                             //       stlxr   w5, x29, [x7]
-    __ ldxr(r5, r16);                                  //       ldxr    x5, [x16]
-    __ ldaxr(r27, r29);                                //       ldaxr   x27, [x29]
-    __ stlr(r0, r29);                                  //       stlr    x0, [x29]
-    __ ldar(r21, r28);                                 //       ldar    x21, [x28]
+    __ stxr(r18, r23, r0);                             //        stxr        w18, x23, [x0]
+    __ stlxr(r30, r5, r22);                            //        stlxr        w30, x5, [x22]
+    __ ldxr(r5, r8);                                   //        ldxr        x5, [x8]
+    __ ldaxr(r20, r16);                                //        ldaxr        x20, [x16]
+    __ stlr(r6, r11);                                  //        stlr        x6, [x11]
+    __ ldar(r6, r27);                                  //        ldar        x6, [x27]
 
 // LoadStoreExclusiveOp
-    __ stxrw(r21, r24, r7);                            //       stxr    w21, w24, [x7]
-    __ stlxrw(r21, r26, r28);                          //       stlxr   w21, w26, [x28]
-    __ ldxrw(r21, r6);                                 //       ldxr    w21, [x6]
-    __ ldaxrw(r15, r30);                               //       ldaxr   w15, [x30]
-    __ stlrw(r19, r3);                                 //       stlr    w19, [x3]
-    __ ldarw(r22, r2);                                 //       ldar    w22, [x2]
+    __ stxrw(r10, r17, r5);                            //        stxr        w10, w17, [x5]
+    __ stlxrw(r22, r9, r12);                           //        stlxr        w22, w9, [x12]
+    __ ldxrw(r27, r8);                                 //        ldxr        w27, [x8]
+    __ ldaxrw(r23, r2);                                //        ldaxr        w23, [x2]
+    __ stlrw(r26, r29);                                //        stlr        w26, [x29]
+    __ ldarw(r13, r10);                                //        ldar        w13, [x10]
 
 // LoadStoreExclusiveOp
-    __ stxrh(r18, r15, r0);                            //       stxrh   w18, w15, [x0]
-    __ stlxrh(r11, r5, r28);                           //       stlxrh  w11, w5, [x28]
-    __ ldxrh(r29, r6);                                 //       ldxrh   w29, [x6]
-    __ ldaxrh(r18, r7);                                //       ldaxrh  w18, [x7]
-    __ stlrh(r25, r28);                                //       stlrh   w25, [x28]
-    __ ldarh(r2, r19);                                 //       ldarh   w2, [x19]
+    __ stxrh(r25, r28, r27);                           //        stxrh        w25, w28, [x27]
+    __ stlxrh(r29, r22, r12);                          //        stlxrh        w29, w22, [x12]
+    __ ldxrh(r22, r28);                                //        ldxrh        w22, [x28]
+    __ ldaxrh(r3, r30);                                //        ldaxrh        w3, [x30]
+    __ stlrh(r24, r15);                                //        stlrh        w24, [x15]
+    __ ldarh(r27, r26);                                //        ldarh        w27, [x26]
 
 // LoadStoreExclusiveOp
-    __ stxrb(r10, r30, r1);                            //       stxrb   w10, w30, [x1]
-    __ stlxrb(r20, r21, r22);                          //       stlxrb  w20, w21, [x22]
-    __ ldxrb(r25, r2);                                 //       ldxrb   w25, [x2]
-    __ ldaxrb(r24, r5);                                //       ldaxrb  w24, [x5]
-    __ stlrb(r16, r3);                                 //       stlrb   w16, [x3]
-    __ ldarb(r22, r29);                                //       ldarb   w22, [x29]
+    __ stxrb(r11, r10, r19);                           //        stxrb        w11, w10, [x19]
+    __ stlxrb(r23, r27, r22);                          //        stlxrb        w23, w27, [x22]
+    __ ldxrb(r24, r16);                                //        ldxrb        w24, [x16]
+    __ ldaxrb(r24, r1);                                //        ldaxrb        w24, [x1]
+    __ stlrb(r5, r29);                                 //        stlrb        w5, [x29]
+    __ ldarb(r24, r16);                                //        ldarb        w24, [x16]
 
 // LoadStoreExclusiveOp
-    __ ldxp(r8, r2, r19);                              //       ldxp    x8, x2, [x19]
-    __ ldaxp(r7, r19, r14);                            //       ldaxp   x7, x19, [x14]
-    __ stxp(r8, r27, r28, r5);                         //       stxp    w8, x27, x28, [x5]
-    __ stlxp(r5, r8, r14, r6);                         //       stlxp   w5, x8, x14, [x6]
+    __ ldxp(r25, r24, r17);                            //        ldxp        x25, x24, [x17]
+    __ ldaxp(r22, r12, r19);                           //        ldaxp        x22, x12, [x19]
+    __ stxp(r0, r26, r21, r25);                        //        stxp        w0, x26, x21, [x25]
+    __ stlxp(r1, r6, r11, r5);                         //        stlxp        w1, x6, x11, [x5]
 
 // LoadStoreExclusiveOp
-    __ ldxpw(r25, r4, r22);                            //       ldxp    w25, w4, [x22]
-    __ ldaxpw(r13, r14, r15);                          //       ldaxp   w13, w14, [x15]
-    __ stxpw(r20, r26, r8, r10);                       //       stxp    w20, w26, w8, [x10]
-    __ stlxpw(r23, r18, r18, r18);                     //       stlxp   w23, w18, w18, [x18]
+    __ ldxpw(r13, r14, r4);                            //        ldxp        w13, w14, [x4]
+    __ ldaxpw(r17, r2, r6);                            //        ldaxp        w17, w2, [x6]
+    __ stxpw(r15, r3, r9, r18);                        //        stxp        w15, w3, w9, [x18]
+    __ stlxpw(r18, r17, r4, r9);                       //        stlxp        w18, w17, w4, [x9]
 
 // base_plus_unscaled_offset
 // LoadStoreOp
-    __ str(r30, Address(r11, 99));                     //       str     x30, [x11, 99]
-    __ strw(r23, Address(r25, -77));                   //       str     w23, [x25, -77]
-    __ strb(r2, Address(r14, 3));                      //       strb    w2, [x14, 3]
-    __ strh(r9, Address(r10, 5));                      //       strh    w9, [x10, 5]
-    __ ldr(r20, Address(r15, 57));                     //       ldr     x20, [x15, 57]
-    __ ldrw(r12, Address(r16, -78));                   //       ldr     w12, [x16, -78]
-    __ ldrb(r22, Address(r26, -3));                    //       ldrb    w22, [x26, -3]
-    __ ldrh(r30, Address(r19, -47));                   //       ldrh    w30, [x19, -47]
-    __ ldrsb(r9, Address(r10, -12));                   //       ldrsb   x9, [x10, -12]
-    __ ldrsh(r28, Address(r17, 14));                   //       ldrsh   x28, [x17, 14]
-    __ ldrshw(r3, Address(r5, 10));                    //       ldrsh   w3, [x5, 10]
-    __ ldrsw(r17, Address(r17, -91));                  //       ldrsw   x17, [x17, -91]
-    __ ldrd(v2, Address(r20, -17));                    //       ldr     d2, [x20, -17]
-    __ ldrs(v22, Address(r7, -10));                    //       ldr     s22, [x7, -10]
-    __ strd(v30, Address(r18, -223));                  //       str     d30, [x18, -223]
-    __ strs(v13, Address(r22, 21));                    //       str     s13, [x22, 21]
+    __ str(r23, Address(r21, -49));                    //        str        x23, [x21, -49]
+    __ strw(r21, Address(r2, 63));                     //        str        w21, [x2, 63]
+    __ strb(r27, Address(r28, 11));                    //        strb        w27, [x28, 11]
+    __ strh(r29, Address(r15, -13));                   //        strh        w29, [x15, -13]
+    __ ldr(r14, Address(r30, -45));                    //        ldr        x14, [x30, -45]
+    __ ldrw(r29, Address(r28, 53));                    //        ldr        w29, [x28, 53]
+    __ ldrb(r20, Address(r26, 7));                     //        ldrb        w20, [x26, 7]
+    __ ldrh(r25, Address(r2, -50));                    //        ldrh        w25, [x2, -50]
+    __ ldrsb(r3, Address(r10, -15));                   //        ldrsb        x3, [x10, -15]
+    __ ldrsh(r14, Address(r15, 19));                   //        ldrsh        x14, [x15, 19]
+    __ ldrshw(r29, Address(r11, -5));                  //        ldrsh        w29, [x11, -5]
+    __ ldrsw(r15, Address(r5, -71));                   //        ldrsw        x15, [x5, -71]
+    __ ldrd(v19, Address(r12, 3));                     //        ldr        d19, [x12, 3]
+    __ ldrs(v12, Address(r27, 42));                    //        ldr        s12, [x27, 42]
+    __ strd(v22, Address(r28, 125));                   //        str        d22, [x28, 125]
+    __ strs(v24, Address(r15, -20));                   //        str        s24, [x15, -20]
 
 // pre
 // LoadStoreOp
-    __ str(r9, Address(__ pre(r18, -112)));            //       str     x9, [x18, -112]!
-    __ strw(r29, Address(__ pre(r23, 11)));            //       str     w29, [x23, 11]!
-    __ strb(r18, Address(__ pre(r12, -1)));            //       strb    w18, [x12, -1]!
-    __ strh(r16, Address(__ pre(r20, -23)));           //       strh    w16, [x20, -23]!
-    __ ldr(r3, Address(__ pre(r29, 9)));               //       ldr     x3, [x29, 9]!
-    __ ldrw(r25, Address(__ pre(r3, 19)));             //       ldr     w25, [x3, 19]!
-    __ ldrb(r1, Address(__ pre(r29, -1)));             //       ldrb    w1, [x29, -1]!
-    __ ldrh(r8, Address(__ pre(r29, -57)));            //       ldrh    w8, [x29, -57]!
-    __ ldrsb(r5, Address(__ pre(r14, -13)));           //       ldrsb   x5, [x14, -13]!
-    __ ldrsh(r10, Address(__ pre(r27, 1)));            //       ldrsh   x10, [x27, 1]!
-    __ ldrshw(r11, Address(__ pre(r10, 25)));          //       ldrsh   w11, [x10, 25]!
-    __ ldrsw(r4, Address(__ pre(r22, -92)));           //       ldrsw   x4, [x22, -92]!
-    __ ldrd(v11, Address(__ pre(r23, 8)));             //       ldr     d11, [x23, 8]!
-    __ ldrs(v25, Address(__ pre(r19, 54)));            //       ldr     s25, [x19, 54]!
-    __ strd(v1, Address(__ pre(r7, -174)));            //       str     d1, [x7, -174]!
-    __ strs(v8, Address(__ pre(r25, 54)));             //       str     s8, [x25, 54]!
+    __ str(r8, Address(__ pre(r28, -24)));             //        str        x8, [x28, -24]!
+    __ strw(r6, Address(__ pre(r15, 37)));             //        str        w6, [x15, 37]!
+    __ strb(r7, Address(__ pre(r1, 7)));               //        strb        w7, [x1, 7]!
+    __ strh(r0, Address(__ pre(r17, 30)));             //        strh        w0, [x17, 30]!
+    __ ldr(r25, Address(__ pre(r29, 84)));             //        ldr        x25, [x29, 84]!
+    __ ldrw(r26, Address(__ pre(r20, -52)));           //        ldr        w26, [x20, -52]!
+    __ ldrb(r26, Address(__ pre(r29, -25)));           //        ldrb        w26, [x29, -25]!
+    __ ldrh(r4, Address(__ pre(r25, 26)));             //        ldrh        w4, [x25, 26]!
+    __ ldrsb(r28, Address(__ pre(r8, -21)));           //        ldrsb        x28, [x8, -21]!
+    __ ldrsh(r17, Address(__ pre(r14, -6)));           //        ldrsh        x17, [x14, -6]!
+    __ ldrshw(r28, Address(__ pre(r23, 10)));          //        ldrsh        w28, [x23, 10]!
+    __ ldrsw(r30, Address(__ pre(r27, -64)));          //        ldrsw        x30, [x27, -64]!
+    __ ldrd(v20, Address(__ pre(r30, -242)));          //        ldr        d20, [x30, -242]!
+    __ ldrs(v17, Address(__ pre(r27, 20)));            //        ldr        s17, [x27, 20]!
+    __ strd(v7, Address(__ pre(r3, 17)));              //        str        d7, [x3, 17]!
+    __ strs(v13, Address(__ pre(r11, -16)));           //        str        s13, [x11, -16]!
 
 // post
 // LoadStoreOp
-    __ str(r5, Address(__ post(r11, 37)));             //       str     x5, [x11], 37
-    __ strw(r24, Address(__ post(r15, 19)));           //       str     w24, [x15], 19
-    __ strb(r15, Address(__ post(r26, -1)));           //       strb    w15, [x26], -1
-    __ strh(r18, Address(__ post(r18, -6)));           //       strh    w18, [x18], -6
-    __ ldr(r7, Address(__ post(r2, -230)));            //       ldr     x7, [x2], -230
-    __ ldrw(r27, Address(__ post(r11, -27)));          //       ldr     w27, [x11], -27
-    __ ldrb(r18, Address(__ post(r3, -25)));           //       ldrb    w18, [x3], -25
-    __ ldrh(r10, Address(__ post(r24, -32)));          //       ldrh    w10, [x24], -32
-    __ ldrsb(r22, Address(__ post(r10, 4)));           //       ldrsb   x22, [x10], 4
-    __ ldrsh(r17, Address(__ post(r12, 25)));          //       ldrsh   x17, [x12], 25
-    __ ldrshw(r8, Address(__ post(r7, -62)));          //       ldrsh   w8, [x7], -62
-    __ ldrsw(r23, Address(__ post(r22, -51)));         //       ldrsw   x23, [x22], -51
-    __ ldrd(v24, Address(__ post(r25, 48)));           //       ldr     d24, [x25], 48
-    __ ldrs(v21, Address(__ post(r12, -10)));          //       ldr     s21, [x12], -10
-    __ strd(v18, Address(__ post(r13, -222)));         //       str     d18, [x13], -222
-    __ strs(v16, Address(__ post(r1, -41)));           //       str     s16, [x1], -41
+    __ str(r6, Address(__ post(r9, -61)));             //        str        x6, [x9], -61
+    __ strw(r16, Address(__ post(r5, -29)));           //        str        w16, [x5], -29
+    __ strb(r29, Address(__ post(r29, 15)));           //        strb        w29, [x29], 15
+    __ strh(r4, Address(__ post(r20, 18)));            //        strh        w4, [x20], 18
+    __ ldr(r19, Address(__ post(r18, 46)));            //        ldr        x19, [x18], 46
+    __ ldrw(r22, Address(__ post(r2, 23)));            //        ldr        w22, [x2], 23
+    __ ldrb(r7, Address(__ post(r3, -30)));            //        ldrb        w7, [x3], -30
+    __ ldrh(r11, Address(__ post(r12, -29)));          //        ldrh        w11, [x12], -29
+    __ ldrsb(r8, Address(__ post(r6, -29)));           //        ldrsb        x8, [x6], -29
+    __ ldrsh(r24, Address(__ post(r23, 4)));           //        ldrsh        x24, [x23], 4
+    __ ldrshw(r17, Address(__ post(r16, 0)));          //        ldrsh        w17, [x16], 0
+    __ ldrsw(r0, Address(__ post(r20, -8)));           //        ldrsw        x0, [x20], -8
+    __ ldrd(v20, Address(__ post(r2, -126)));          //        ldr        d20, [x2], -126
+    __ ldrs(v19, Address(__ post(r30, -104)));         //        ldr        s19, [x30], -104
+    __ strd(v4, Address(__ post(r17, 118)));           //        str        d4, [x17], 118
+    __ strs(v21, Address(__ post(r19, -112)));         //        str        s21, [x19], -112
 
 // base_plus_reg
 // LoadStoreOp
-    __ str(r2, Address(r22, r15, Address::sxtw(0)));   //       str     x2, [x22, w15, sxtw #0]
-    __ strw(r2, Address(r16, r29, Address::lsl(0)));   //       str     w2, [x16, x29, lsl #0]
-    __ strb(r20, Address(r18, r14, Address::uxtw(0))); //       strb    w20, [x18, w14, uxtw #0]
-    __ strh(r6, Address(r19, r20, Address::sxtx(1)));  //       strh    w6, [x19, x20, sxtx #1]
-    __ ldr(r14, Address(r29, r14, Address::sxtw(0)));  //       ldr     x14, [x29, w14, sxtw #0]
-    __ ldrw(r16, Address(r20, r12, Address::sxtw(2))); //       ldr     w16, [x20, w12, sxtw #2]
-    __ ldrb(r9, Address(r12, r0, Address::sxtw(0)));   //       ldrb    w9, [x12, w0, sxtw #0]
-    __ ldrh(r12, Address(r17, r3, Address::lsl(1)));   //       ldrh    w12, [x17, x3, lsl #1]
-    __ ldrsb(r2, Address(r17, r3, Address::sxtx(0)));  //       ldrsb   x2, [x17, x3, sxtx #0]
-    __ ldrsh(r7, Address(r1, r17, Address::uxtw(1)));  //       ldrsh   x7, [x1, w17, uxtw #1]
-    __ ldrshw(r25, Address(r15, r18, Address::sxtw(1))); //     ldrsh   w25, [x15, w18, sxtw #1]
-    __ ldrsw(r23, Address(r21, r12, Address::lsl(0))); //       ldrsw   x23, [x21, x12, lsl #0]
-    __ ldrd(v5, Address(r13, r8, Address::lsl(3)));    //       ldr     d5, [x13, x8, lsl #3]
-    __ ldrs(v3, Address(r10, r22, Address::lsl(2)));   //       ldr     s3, [x10, x22, lsl #2]
-    __ strd(v14, Address(r2, r27, Address::sxtw(0)));  //       str     d14, [x2, w27, sxtw #0]
-    __ strs(v20, Address(r6, r25, Address::lsl(0)));   //       str     s20, [x6, x25, lsl #0]
+    __ str(r26, Address(r2, r19, Address::lsl(3)));    //        str        x26, [x2, x19, lsl #3]
+    __ strw(r9, Address(r0, r15, Address::sxtw(2)));   //        str        w9, [x0, w15, sxtw #2]
+    __ strb(r26, Address(r12, r1, Address::lsl(0)));   //        strb        w26, [x12, x1, lsl #0]
+    __ strh(r21, Address(r11, r10, Address::lsl(1)));  //        strh        w21, [x11, x10, lsl #1]
+    __ ldr(r16, Address(r23, r16, Address::sxtx(0)));  //        ldr        x16, [x23, x16, sxtx #0]
+    __ ldrw(r10, Address(r11, r17, Address::sxtw(2))); //        ldr        w10, [x11, w17, sxtw #2]
+    __ ldrb(r13, Address(r23, r11, Address::lsl(0)));  //        ldrb        w13, [x23, x11, lsl #0]
+    __ ldrh(r27, Address(r4, r21, Address::lsl(0)));   //        ldrh        w27, [x4, x21, lsl #0]
+    __ ldrsb(r26, Address(r8, r15, Address::sxtw(0))); //        ldrsb        x26, [x8, w15, sxtw #0]
+    __ ldrsh(r21, Address(r10, r2, Address::sxtw(0))); //        ldrsh        x21, [x10, w2, sxtw #0]
+    __ ldrshw(r8, Address(r30, r14, Address::lsl(0))); //        ldrsh        w8, [x30, x14, lsl #0]
+    __ ldrsw(r29, Address(r14, r20, Address::sxtx(2))); //        ldrsw        x29, [x14, x20, sxtx #2]
+    __ ldrd(v30, Address(r27, r22, Address::sxtx(0))); //        ldr        d30, [x27, x22, sxtx #0]
+    __ ldrs(v13, Address(r9, r22, Address::lsl(0)));   //        ldr        s13, [x9, x22, lsl #0]
+    __ strd(v8, Address(r25, r17, Address::sxtw(3)));  //        str        d8, [x25, w17, sxtw #3]
+    __ strs(v1, Address(r24, r5, Address::uxtw(2)));   //        str        s1, [x24, w5, uxtw #2]
 
 // base_plus_scaled_offset
 // LoadStoreOp
-    __ str(r30, Address(r7, 16256));                   //       str     x30, [x7, 16256]
-    __ strw(r15, Address(r8, 7588));                   //       str     w15, [x8, 7588]
-    __ strb(r11, Address(r0, 1866));                   //       strb    w11, [x0, 1866]
-    __ strh(r3, Address(r17, 3734));                   //       strh    w3, [x17, 3734]
-    __ ldr(r2, Address(r7, 14224));                    //       ldr     x2, [x7, 14224]
-    __ ldrw(r5, Address(r9, 7396));                    //       ldr     w5, [x9, 7396]
-    __ ldrb(r28, Address(r9, 1721));                   //       ldrb    w28, [x9, 1721]
-    __ ldrh(r2, Address(r20, 3656));                   //       ldrh    w2, [x20, 3656]
-    __ ldrsb(r22, Address(r14, 1887));                 //       ldrsb   x22, [x14, 1887]
-    __ ldrsh(r8, Address(r0, 4080));                   //       ldrsh   x8, [x0, 4080]
-    __ ldrshw(r0, Address(r30, 3916));                 //       ldrsh   w0, [x30, 3916]
-    __ ldrsw(r24, Address(r19, 6828));                 //       ldrsw   x24, [x19, 6828]
-    __ ldrd(v24, Address(r12, 13032));                 //       ldr     d24, [x12, 13032]
-    __ ldrs(v8, Address(r8, 7452));                    //       ldr     s8, [x8, 7452]
-    __ strd(v10, Address(r15, 15992));                 //       str     d10, [x15, 15992]
-    __ strs(v26, Address(r19, 6688));                  //       str     s26, [x19, 6688]
+    __ str(r10, Address(r21, 14496));                  //        str        x10, [x21, 14496]
+    __ strw(r18, Address(r29, 7228));                  //        str        w18, [x29, 7228]
+    __ strb(r23, Address(r3, 2018));                   //        strb        w23, [x3, 2018]
+    __ strh(r28, Address(r11, 3428));                  //        strh        w28, [x11, 3428]
+    __ ldr(r24, Address(r26, 14376));                  //        ldr        x24, [x26, 14376]
+    __ ldrw(r21, Address(r2, 6972));                   //        ldr        w21, [x2, 6972]
+    __ ldrb(r4, Address(r5, 1848));                    //        ldrb        w4, [x5, 1848]
+    __ ldrh(r14, Address(r14, 3112));                  //        ldrh        w14, [x14, 3112]
+    __ ldrsb(r4, Address(r27, 1959));                  //        ldrsb        x4, [x27, 1959]
+    __ ldrsh(r4, Address(r27, 3226));                  //        ldrsh        x4, [x27, 3226]
+    __ ldrshw(r10, Address(r28, 3286));                //        ldrsh        w10, [x28, 3286]
+    __ ldrsw(r10, Address(r17, 7912));                 //        ldrsw        x10, [x17, 7912]
+    __ ldrd(v13, Address(r28, 13400));                 //        ldr        d13, [x28, 13400]
+    __ ldrs(v24, Address(r3, 7596));                   //        ldr        s24, [x3, 7596]
+    __ strd(v2, Address(r12, 15360));                  //        str        d2, [x12, 15360]
+    __ strs(v17, Address(r1, 6492));                   //        str        s17, [x1, 6492]
 
 // pcrel
 // LoadStoreOp
-    __ ldr(r10, forth);                                //       ldr     x10, forth
-    __ ldrw(r3, __ pc());                              //       ldr     w3, .
+    __ ldr(r16, __ pc());                              //        ldr        x16, .
+    __ ldrw(r13, __ pc());                             //        ldr        w13, .
 
 // LoadStoreOp
-    __ prfm(Address(r23, 9));                          //       prfm    PLDL1KEEP, [x23, 9]
+    __ prfm(Address(r18, -127));                       //        prfm        PLDL1KEEP, [x18, -127]
 
 // LoadStoreOp
-    __ prfm(back);                                     //       prfm    PLDL1KEEP, back
+    __ prfm(back);                                     //        prfm        PLDL1KEEP, back
 
 // LoadStoreOp
-    __ prfm(Address(r3, r8, Address::uxtw(0)));        //       prfm    PLDL1KEEP, [x3, w8, uxtw #0]
+    __ prfm(Address(r20, r2, Address::lsl(3)));        //        prfm        PLDL1KEEP, [x20, x2, lsl #3]
 
 // LoadStoreOp
-    __ prfm(Address(r11, 15080));                      //       prfm    PLDL1KEEP, [x11, 15080]
+    __ prfm(Address(r9, 13808));                       //        prfm        PLDL1KEEP, [x9, 13808]
 
 // AddSubCarryOp
-    __ adcw(r13, r9, r28);                             //       adc     w13, w9, w28
-    __ adcsw(r27, r19, r28);                           //       adcs    w27, w19, w28
-    __ sbcw(r19, r18, r6);                             //       sbc     w19, w18, w6
-    __ sbcsw(r14, r20, r3);                            //       sbcs    w14, w20, w3
-    __ adc(r16, r14, r8);                              //       adc     x16, x14, x8
-    __ adcs(r0, r29, r8);                              //       adcs    x0, x29, x8
-    __ sbc(r8, r24, r20);                              //       sbc     x8, x24, x20
-    __ sbcs(r12, r28, r0);                             //       sbcs    x12, x28, x0
+    __ adcw(r8, r23, r2);                              //        adc        w8, w23, w2
+    __ adcsw(r24, r3, r19);                            //        adcs        w24, w3, w19
+    __ sbcw(r22, r24, r29);                            //        sbc        w22, w24, w29
+    __ sbcsw(r12, r27, r3);                            //        sbcs        w12, w27, w3
+    __ adc(r11, r23, r1);                              //        adc        x11, x23, x1
+    __ adcs(r29, r5, r23);                             //        adcs        x29, x5, x23
+    __ sbc(r9, r25, r12);                              //        sbc        x9, x25, x12
+    __ sbcs(r12, r0, r22);                             //        sbcs        x12, x0, x22
 
 // AddSubExtendedOp
-    __ addw(r23, r6, r16, ext::uxtb, 4);               //       add     w23, w6, w16, uxtb #4
-    __ addsw(r25, r25, r23, ext::sxth, 2);             //       adds    w25, w25, w23, sxth #2
-    __ sub(r26, r22, r4, ext::uxtx, 1);                //       sub     x26, x22, x4, uxtx #1
-    __ subsw(r17, r29, r19, ext::sxtx, 3);             //       subs    w17, w29, w19, sxtx #3
-    __ add(r11, r30, r21, ext::uxtb, 3);               //       add     x11, x30, x21, uxtb #3
-    __ adds(r16, r19, r0, ext::sxtb, 2);               //       adds    x16, x19, x0, sxtb #2
-    __ sub(r11, r9, r25, ext::sxtx, 1);                //       sub     x11, x9, x25, sxtx #1
-    __ subs(r17, r20, r12, ext::sxtb, 4);              //       subs    x17, x20, x12, sxtb #4
+    __ addw(r26, r12, r3, ext::uxtw, 1);               //        add        w26, w12, w3, uxtw #1
+    __ addsw(r20, r16, r18, ext::sxtb, 2);             //        adds        w20, w16, w18, sxtb #2
+    __ sub(r30, r30, r7, ext::uxtw, 2);                //        sub        x30, x30, x7, uxtw #2
+    __ subsw(r11, r21, r2, ext::uxth, 3);              //        subs        w11, w21, w2, uxth #3
+    __ add(r2, r26, r1, ext::uxtw, 2);                 //        add        x2, x26, x1, uxtw #2
+    __ adds(r18, r29, r20, ext::sxth, 1);              //        adds        x18, x29, x20, sxth #1
+    __ sub(r14, r16, r4, ext::uxtw, 4);                //        sub        x14, x16, x4, uxtw #4
+    __ subs(r0, r17, r23, ext::sxtb, 3);               //        subs        x0, x17, x23, sxtb #3
 
 // ConditionalCompareOp
-    __ ccmnw(r13, r11, 3u, Assembler::LE);             //       ccmn    w13, w11, #3, LE
-    __ ccmpw(r13, r12, 2u, Assembler::HI);             //       ccmp    w13, w12, #2, HI
-    __ ccmn(r3, r2, 12u, Assembler::NE);               //       ccmn    x3, x2, #12, NE
-    __ ccmp(r7, r21, 3u, Assembler::VS);               //       ccmp    x7, x21, #3, VS
+    __ ccmnw(r20, r22, 3u, Assembler::PL);             //        ccmn        w20, w22, #3, PL
+    __ ccmpw(r25, r2, 1u, Assembler::EQ);              //        ccmp        w25, w2, #1, EQ
+    __ ccmn(r18, r24, 7u, Assembler::GT);              //        ccmn        x18, x24, #7, GT
+    __ ccmp(r8, r13, 6u, Assembler::PL);               //        ccmp        x8, x13, #6, PL
 
 // ConditionalCompareImmedOp
-    __ ccmnw(r2, 14, 4, Assembler::CC);                //       ccmn    w2, #14, #4, CC
-    __ ccmpw(r17, 17, 6, Assembler::PL);               //       ccmp    w17, #17, #6, PL
-    __ ccmn(r10, 12, 0, Assembler::CS);                //       ccmn    x10, #12, #0, CS
-    __ ccmp(r21, 18, 14, Assembler::GE);               //       ccmp    x21, #18, #14, GE
+    __ ccmnw(r9, 2, 4, Assembler::VS);                 //        ccmn        w9, #2, #4, VS
+    __ ccmpw(r2, 27, 7, Assembler::EQ);                //        ccmp        w2, #27, #7, EQ
+    __ ccmn(r16, 1, 2, Assembler::CC);                 //        ccmn        x16, #1, #2, CC
+    __ ccmp(r17, 31, 3, Assembler::LT);                //        ccmp        x17, #31, #3, LT
 
 // ConditionalSelectOp
-    __ cselw(r21, r13, r12, Assembler::GT);            //       csel    w21, w13, w12, GT
-    __ csincw(r10, r27, r15, Assembler::LS);           //       csinc   w10, w27, w15, LS
-    __ csinvw(r0, r13, r9, Assembler::HI);             //       csinv   w0, w13, w9, HI
-    __ csnegw(r18, r4, r26, Assembler::VS);            //       csneg   w18, w4, w26, VS
-    __ csel(r12, r29, r7, Assembler::LS);              //       csel    x12, x29, x7, LS
-    __ csinc(r6, r7, r20, Assembler::VC);              //       csinc   x6, x7, x20, VC
-    __ csinv(r22, r21, r3, Assembler::LE);             //       csinv   x22, x21, x3, LE
-    __ csneg(r19, r12, r27, Assembler::LS);            //       csneg   x19, x12, x27, LS
+    __ cselw(r23, r27, r23, Assembler::LS);            //        csel        w23, w27, w23, LS
+    __ csincw(r10, r0, r6, Assembler::VS);             //        csinc        w10, w0, w6, VS
+    __ csinvw(r11, r0, r9, Assembler::CC);             //        csinv        w11, w0, w9, CC
+    __ csnegw(r17, r27, r18, Assembler::LO);           //        csneg        w17, w27, w18, LO
+    __ csel(r12, r16, r11, Assembler::VC);             //        csel        x12, x16, x11, VC
+    __ csinc(r6, r28, r6, Assembler::HI);              //        csinc        x6, x28, x6, HI
+    __ csinv(r13, r27, r26, Assembler::VC);            //        csinv        x13, x27, x26, VC
+    __ csneg(r29, r22, r18, Assembler::PL);            //        csneg        x29, x22, x18, PL
 
 // TwoRegOp
-    __ rbitw(r0, r16);                                 //       rbit    w0, w16
-    __ rev16w(r17, r23);                               //       rev16   w17, w23
-    __ revw(r17, r14);                                 //       rev     w17, w14
-    __ clzw(r24, r30);                                 //       clz     w24, w30
-    __ clsw(r24, r22);                                 //       cls     w24, w22
-    __ rbit(r3, r17);                                  //       rbit    x3, x17
-    __ rev16(r12, r13);                                //       rev16   x12, x13
-    __ rev32(r9, r22);                                 //       rev32   x9, x22
-    __ rev(r0, r0);                                    //       rev     x0, x0
-    __ clz(r5, r16);                                   //       clz     x5, x16
-    __ cls(r25, r22);                                  //       cls     x25, x22
+    __ rbitw(r12, r19);                                //        rbit        w12, w19
+    __ rev16w(r23, r18);                               //        rev16        w23, w18
+    __ revw(r9, r28);                                  //        rev        w9, w28
+    __ clzw(r2, r19);                                  //        clz        w2, w19
+    __ clsw(r25, r29);                                 //        cls        w25, w29
+    __ rbit(r4, r23);                                  //        rbit        x4, x23
+    __ rev16(r29, r18);                                //        rev16        x29, x18
+    __ rev32(r7, r8);                                  //        rev32        x7, x8
+    __ rev(r13, r17);                                  //        rev        x13, x17
+    __ clz(r17, r0);                                   //        clz        x17, x0
+    __ cls(r18, r26);                                  //        cls        x18, x26
 
 // ThreeRegOp
-    __ udivw(r29, r4, r0);                             //       udiv    w29, w4, w0
-    __ sdivw(r0, r29, r29);                            //       sdiv    w0, w29, w29
-    __ lslvw(r5, r17, r21);                            //       lslv    w5, w17, w21
-    __ lsrvw(r9, r9, r18);                             //       lsrv    w9, w9, w18
-    __ asrvw(r1, r27, r8);                             //       asrv    w1, w27, w8
-    __ rorvw(r18, r20, r13);                           //       rorv    w18, w20, w13
-    __ udiv(r8, r25, r12);                             //       udiv    x8, x25, x12
-    __ sdiv(r7, r5, r28);                              //       sdiv    x7, x5, x28
-    __ lslv(r5, r17, r27);                             //       lslv    x5, x17, x27
-    __ lsrv(r23, r26, r20);                            //       lsrv    x23, x26, x20
-    __ asrv(r28, r8, r28);                             //       asrv    x28, x8, x28
-    __ rorv(r3, r29, r4);                              //       rorv    x3, x29, x4
+    __ udivw(r11, r12, r16);                           //        udiv        w11, w12, w16
+    __ sdivw(r4, r9, r7);                              //        sdiv        w4, w9, w7
+    __ lslvw(r12, r7, r16);                            //        lslv        w12, w7, w16
+    __ lsrvw(r19, r16, r23);                           //        lsrv        w19, w16, w23
+    __ asrvw(r7, r4, r6);                              //        asrv        w7, w4, w6
+    __ rorvw(r21, r20, r23);                           //        rorv        w21, w20, w23
+    __ udiv(r16, r12, r28);                            //        udiv        x16, x12, x28
+    __ sdiv(r4, r12, r13);                             //        sdiv        x4, x12, x13
+    __ lslv(r9, r13, r7);                              //        lslv        x9, x13, x7
+    __ lsrv(r28, r27, r15);                            //        lsrv        x28, x27, x15
+    __ asrv(r20, r30, r14);                            //        asrv        x20, x30, x14
+    __ rorv(r14, r18, r30);                            //        rorv        x14, x18, x30
+    __ umulh(r3, r11, r7);                             //        umulh        x3, x11, x7
+    __ smulh(r23, r20, r24);                           //        smulh        x23, x20, x24
 
 // FourRegMulOp
-    __ maddw(r17, r14, r26, r21);                      //       madd    w17, w14, w26, w21
-    __ msubw(r1, r30, r11, r11);                       //       msub    w1, w30, w11, w11
-    __ madd(r1, r17, r6, r28);                         //       madd    x1, x17, x6, x28
-    __ msub(r30, r6, r30, r8);                         //       msub    x30, x6, x30, x8
-    __ smaddl(r21, r6, r14, r8);                       //       smaddl  x21, w6, w14, x8
-    __ smsubl(r10, r10, r24, r19);                     //       smsubl  x10, w10, w24, x19
-    __ umaddl(r20, r18, r14, r24);                     //       umaddl  x20, w18, w14, x24
-    __ umsubl(r18, r2, r5, r5);                        //       umsubl  x18, w2, w5, x5
+    __ maddw(r2, r5, r21, r9);                         //        madd        w2, w5, w21, w9
+    __ msubw(r24, r24, r4, r8);                        //        msub        w24, w24, w4, w8
+    __ madd(r11, r12, r15, r19);                       //        madd        x11, x12, x15, x19
+    __ msub(r29, r25, r12, r25);                       //        msub        x29, x25, x12, x25
+    __ smaddl(r17, r11, r12, r22);                     //        smaddl        x17, w11, w12, x22
+    __ smsubl(r28, r3, r20, r18);                      //        smsubl        x28, w3, w20, x18
+    __ umaddl(r7, r4, r28, r26);                       //        umaddl        x7, w4, w28, x26
+    __ umsubl(r22, r10, r17, r5);                      //        umsubl        x22, w10, w17, x5
 
 // ThreeRegFloatOp
-    __ fmuls(v8, v18, v13);                            //       fmul    s8, s18, s13
-    __ fdivs(v2, v14, v28);                            //       fdiv    s2, s14, s28
-    __ fadds(v15, v12, v28);                           //       fadd    s15, s12, s28
-    __ fsubs(v0, v12, v1);                             //       fsub    s0, s12, s1
-    __ fmuls(v15, v29, v4);                            //       fmul    s15, s29, s4
-    __ fmuld(v12, v1, v23);                            //       fmul    d12, d1, d23
-    __ fdivd(v27, v8, v18);                            //       fdiv    d27, d8, d18
-    __ faddd(v23, v20, v11);                           //       fadd    d23, d20, d11
-    __ fsubd(v8, v12, v18);                            //       fsub    d8, d12, d18
-    __ fmuld(v26, v24, v23);                           //       fmul    d26, d24, d23
+    __ fmuls(v17, v3, v17);                            //        fmul        s17, s3, s17
+    __ fdivs(v11, v17, v6);                            //        fdiv        s11, s17, s6
+    __ fadds(v29, v7, v9);                             //        fadd        s29, s7, s9
+    __ fsubs(v7, v12, v19);                            //        fsub        s7, s12, s19
+    __ fmuls(v0, v23, v3);                             //        fmul        s0, s23, s3
+    __ fmuld(v26, v3, v21);                            //        fmul        d26, d3, d21
+    __ fdivd(v0, v19, v5);                             //        fdiv        d0, d19, d5
+    __ faddd(v0, v26, v9);                             //        fadd        d0, d26, d9
+    __ fsubd(v25, v21, v21);                           //        fsub        d25, d21, d21
+    __ fmuld(v16, v13, v19);                           //        fmul        d16, d13, d19
 
 // FourRegFloatOp
-    __ fmadds(v21, v23, v13, v25);                     //       fmadd   s21, s23, s13, s25
-    __ fmsubs(v22, v10, v1, v14);                      //       fmsub   s22, s10, s1, s14
-    __ fnmadds(v14, v20, v2, v30);                     //       fnmadd  s14, s20, s2, s30
-    __ fnmadds(v7, v29, v22, v22);                     //       fnmadd  s7, s29, s22, s22
-    __ fmaddd(v13, v5, v15, v5);                       //       fmadd   d13, d5, d15, d5
-    __ fmsubd(v14, v12, v5, v10);                      //       fmsub   d14, d12, d5, d10
-    __ fnmaddd(v10, v19, v0, v1);                      //       fnmadd  d10, d19, d0, d1
-    __ fnmaddd(v20, v2, v2, v0);                       //       fnmadd  d20, d2, d2, d0
+    __ fmadds(v29, v18, v0, v16);                      //        fmadd        s29, s18, s0, s16
+    __ fmsubs(v23, v13, v29, v5);                      //        fmsub        s23, s13, s29, s5
+    __ fnmadds(v9, v7, v10, v14);                      //        fnmadd        s9, s7, s10, s14
+    __ fnmadds(v25, v28, v15, v23);                    //        fnmadd        s25, s28, s15, s23
+    __ fmaddd(v6, v13, v21, v17);                      //        fmadd        d6, d13, d21, d17
+    __ fmsubd(v3, v21, v2, v7);                        //        fmsub        d3, d21, d2, d7
+    __ fnmaddd(v10, v25, v5, v17);                     //        fnmadd        d10, d25, d5, d17
+    __ fnmaddd(v14, v14, v20, v18);                    //        fnmadd        d14, d14, d20, d18
 
 // TwoRegFloatOp
-    __ fmovs(v25, v9);                                 //       fmov    s25, s9
-    __ fabss(v20, v4);                                 //       fabs    s20, s4
-    __ fnegs(v3, v27);                                 //       fneg    s3, s27
-    __ fsqrts(v1, v2);                                 //       fsqrt   s1, s2
-    __ fcvts(v30, v0);                                 //       fcvt    d30, s0
-    __ fmovd(v12, v4);                                 //       fmov    d12, d4
-    __ fabsd(v1, v27);                                 //       fabs    d1, d27
-    __ fnegd(v8, v22);                                 //       fneg    d8, d22
-    __ fsqrtd(v11, v11);                               //       fsqrt   d11, d11
-    __ fcvtd(v22, v28);                                //       fcvt    s22, d28
+    __ fmovs(v15, v2);                                 //        fmov        s15, s2
+    __ fabss(v18, v7);                                 //        fabs        s18, s7
+    __ fnegs(v3, v6);                                  //        fneg        s3, s6
+    __ fsqrts(v12, v1);                                //        fsqrt        s12, s1
+    __ fcvts(v9, v0);                                  //        fcvt        d9, s0
+    __ fmovd(v4, v5);                                  //        fmov        d4, d5
+    __ fabsd(v3, v15);                                 //        fabs        d3, d15
+    __ fnegd(v17, v25);                                //        fneg        d17, d25
+    __ fsqrtd(v12, v24);                               //        fsqrt        d12, d24
+    __ fcvtd(v21, v5);                                 //        fcvt        s21, d5
 
 // FloatConvertOp
-    __ fcvtzsw(r28, v22);                              //       fcvtzs  w28, s22
-    __ fcvtzs(r20, v27);                               //       fcvtzs  x20, s27
-    __ fcvtzdw(r14, v0);                               //       fcvtzs  w14, d0
-    __ fcvtzd(r26, v11);                               //       fcvtzs  x26, d11
-    __ scvtfws(v28, r22);                              //       scvtf   s28, w22
-    __ scvtfs(v16, r10);                               //       scvtf   s16, x10
-    __ scvtfwd(v8, r21);                               //       scvtf   d8, w21
-    __ scvtfd(v21, r28);                               //       scvtf   d21, x28
-    __ fmovs(r24, v24);                                //       fmov    w24, s24
-    __ fmovd(r8, v19);                                 //       fmov    x8, d19
-    __ fmovs(v8, r12);                                 //       fmov    s8, w12
-    __ fmovd(v6, r7);                                  //       fmov    d6, x7
+    __ fcvtzsw(r4, v21);                               //        fcvtzs        w4, s21
+    __ fcvtzs(r27, v3);                                //        fcvtzs        x27, s3
+    __ fcvtzdw(r29, v8);                               //        fcvtzs        w29, d8
+    __ fcvtzd(r9, v21);                                //        fcvtzs        x9, d21
+    __ scvtfws(v20, r29);                              //        scvtf        s20, w29
+    __ scvtfs(v7, r8);                                 //        scvtf        s7, x8
+    __ scvtfwd(v12, r21);                              //        scvtf        d12, w21
+    __ scvtfd(v16, r21);                               //        scvtf        d16, x21
+    __ fmovs(r18, v5);                                 //        fmov        w18, s5
+    __ fmovd(r25, v8);                                 //        fmov        x25, d8
+    __ fmovs(v18, r26);                                //        fmov        s18, w26
+    __ fmovd(v0, r11);                                 //        fmov        d0, x11
 
 // TwoRegFloatOp
-    __ fcmps(v30, v16);                                //       fcmp    s30, s16
-    __ fcmpd(v25, v11);                                //       fcmp    d25, d11
-    __ fcmps(v11, 0.0);                                //       fcmp    s11, #0.0
-    __ fcmpd(v11, 0.0);                                //       fcmp    d11, #0.0
+    __ fcmps(v16, v6);                                 //        fcmp        s16, s6
+    __ fcmpd(v16, v29);                                //        fcmp        d16, d29
+    __ fcmps(v30, 0.0);                                //        fcmp        s30, #0.0
+    __ fcmpd(v9, 0.0);                                 //        fcmp        d9, #0.0
+
+// LoadStorePairOp
+    __ stpw(r27, r4, Address(r12, -16));               //        stp        w27, w4, [x12, #-16]
+    __ ldpw(r3, r9, Address(r10, 80));                 //        ldp        w3, w9, [x10, #80]
+    __ ldpsw(r16, r3, Address(r3, 64));                //        ldpsw        x16, x3, [x3, #64]
+    __ stp(r10, r28, Address(r19, -192));              //        stp        x10, x28, [x19, #-192]
+    __ ldp(r19, r18, Address(r7, -192));               //        ldp        x19, x18, [x7, #-192]
+
+// LoadStorePairOp
+    __ stpw(r10, r16, Address(__ pre(r30, 16)));       //        stp        w10, w16, [x30, #16]!
+    __ ldpw(r2, r4, Address(__ pre(r18, -240)));       //        ldp        w2, w4, [x18, #-240]!
+    __ ldpsw(r24, r19, Address(__ pre(r13, 48)));      //        ldpsw        x24, x19, [x13, #48]!
+    __ stp(r17, r0, Address(__ pre(r24, 0)));          //        stp        x17, x0, [x24, #0]!
+    __ ldp(r14, r26, Address(__ pre(r3, -192)));       //        ldp        x14, x26, [x3, #-192]!
+
+// LoadStorePairOp
+    __ stpw(r22, r1, Address(__ post(r0, 80)));        //        stp        w22, w1, [x0], #80
+    __ ldpw(r18, r10, Address(__ post(r0, -16)));      //        ldp        w18, w10, [x0], #-16
+    __ ldpsw(r24, r24, Address(__ post(r22, -16)));    //        ldpsw        x24, x24, [x22], #-16
+    __ stp(r12, r12, Address(__ post(r4, 80)));        //        stp        x12, x12, [x4], #80
+    __ ldp(r4, r9, Address(__ post(r19, -240)));       //        ldp        x4, x9, [x19], #-240
 
 // LoadStorePairOp
-    __ stpw(r29, r12, Address(r17, 128));              //       stp     w29, w12, [x17, #128]
-    __ ldpw(r22, r18, Address(r14, -96));              //       ldp     w22, w18, [x14, #-96]
-    __ ldpsw(r11, r16, Address(r1, 64));               //       ldpsw   x11, x16, [x1, #64]
-    __ stp(r0, r11, Address(r26, 112));                //       stp     x0, x11, [x26, #112]
-    __ ldp(r7, r1, Address(r26, 16));                  //       ldp     x7, x1, [x26, #16]
-
-// LoadStorePairOp
-    __ stpw(r10, r7, Address(__ pre(r24, 0)));         //       stp     w10, w7, [x24, #0]!
-    __ ldpw(r7, r28, Address(__ pre(r24, -256)));      //       ldp     w7, w28, [x24, #-256]!
-    __ ldpsw(r25, r28, Address(__ pre(r21, -240)));    //       ldpsw   x25, x28, [x21, #-240]!
-    __ stp(r20, r18, Address(__ pre(r14, -16)));       //       stp     x20, x18, [x14, #-16]!
-    __ ldp(r8, r10, Address(__ pre(r13, 80)));         //       ldp     x8, x10, [x13, #80]!
+    __ stnpw(r18, r26, Address(r6, -224));             //        stnp        w18, w26, [x6, #-224]
+    __ ldnpw(r21, r20, Address(r1, 112));              //        ldnp        w21, w20, [x1, #112]
+    __ stnp(r25, r29, Address(r20, -224));             //        stnp        x25, x29, [x20, #-224]
+    __ ldnp(r1, r5, Address(r23, 112));                //        ldnp        x1, x5, [x23, #112]
 
-// LoadStorePairOp
-    __ stpw(r26, r24, Address(__ post(r2, -128)));     //       stp     w26, w24, [x2], #-128
-    __ ldpw(r2, r25, Address(__ post(r21, -192)));     //       ldp     w2, w25, [x21], #-192
-    __ ldpsw(r17, r2, Address(__ post(r21, -144)));    //       ldpsw   x17, x2, [x21], #-144
-    __ stp(r12, r10, Address(__ post(r11, 96)));       //       stp     x12, x10, [x11], #96
-    __ ldp(r24, r6, Address(__ post(r17, -32)));       //       ldp     x24, x6, [x17], #-32
+// LdStSIMDOp
+    __ ld1(v4, __ T8B, Address(r20));                  //        ld1        {v4.8B}, [x20]
+    __ ld1(v24, v25, __ T16B, Address(__ post(r10, 32))); //        ld1        {v24.16B, v25.16B}, [x10], 32
+    __ ld1(v24, v25, v26, __ T1D, Address(__ post(r6, r15))); //        ld1        {v24.1D, v25.1D, v26.1D}, [x6], x15
+    __ ld1(v3, v4, v5, v6, __ T8H, Address(__ post(r4, 64))); //        ld1        {v3.8H, v4.8H, v5.8H, v6.8H}, [x4], 64
+    __ ld1r(v2, __ T8B, Address(r6));                  //        ld1r        {v2.8B}, [x6]
+    __ ld1r(v13, __ T4S, Address(__ post(r14, 4)));    //        ld1r        {v13.4S}, [x14], 4
+    __ ld1r(v15, __ T1D, Address(__ post(r21, r24)));  //        ld1r        {v15.1D}, [x21], x24
+    __ ld2(v9, v10, __ T2D, Address(r21));             //        ld2        {v9.2D, v10.2D}, [x21]
+    __ ld2(v29, v30, __ T4H, Address(__ post(r21, 16))); //        ld2        {v29.4H, v30.4H}, [x21], 16
+    __ ld2r(v8, v9, __ T16B, Address(r14));            //        ld2r        {v8.16B, v9.16B}, [x14]
+    __ ld2r(v7, v8, __ T2S, Address(__ post(r20, 8))); //        ld2r        {v7.2S, v8.2S}, [x20], 8
+    __ ld2r(v28, v29, __ T2D, Address(__ post(r3, r3))); //        ld2r        {v28.2D, v29.2D}, [x3], x3
+    __ ld3(v27, v28, v29, __ T4S, Address(__ post(r11, r29))); //        ld3        {v27.4S, v28.4S, v29.4S}, [x11], x29
+    __ ld3(v16, v17, v18, __ T2S, Address(r10));       //        ld3        {v16.2S, v17.2S, v18.2S}, [x10]
+    __ ld3r(v21, v22, v23, __ T8H, Address(r12));      //        ld3r        {v21.8H, v22.8H, v23.8H}, [x12]
+    __ ld3r(v4, v5, v6, __ T4S, Address(__ post(r29, 12))); //        ld3r        {v4.4S, v5.4S, v6.4S}, [x29], 12
+    __ ld3r(v24, v25, v26, __ T1D, Address(__ post(r9, r19))); //        ld3r        {v24.1D, v25.1D, v26.1D}, [x9], x19
+    __ ld4(v10, v11, v12, v13, __ T8H, Address(__ post(r3, 64))); //        ld4        {v10.8H, v11.8H, v12.8H, v13.8H}, [x3], 64
+    __ ld4(v27, v28, v29, v30, __ T8B, Address(__ post(r28, r9))); //        ld4        {v27.8B, v28.8B, v29.8B, v30.8B}, [x28], x9
+    __ ld4r(v21, v22, v23, v24, __ T8B, Address(r30)); //        ld4r        {v21.8B, v22.8B, v23.8B, v24.8B}, [x30]
+    __ ld4r(v23, v24, v25, v26, __ T4H, Address(__ post(r14, 8))); //        ld4r        {v23.4H, v24.4H, v25.4H, v26.4H}, [x14], 8
+    __ ld4r(v4, v5, v6, v7, __ T2S, Address(__ post(r13, r20))); //        ld4r        {v4.2S, v5.2S, v6.2S, v7.2S}, [x13], x20
 
-// LoadStorePairOp
-    __ stnpw(r3, r30, Address(r14, -224));             //       stnp    w3, w30, [x14, #-224]
-    __ ldnpw(r15, r20, Address(r26, -144));            //       ldnp    w15, w20, [x26, #-144]
-    __ stnp(r22, r25, Address(r12, -128));             //       stnp    x22, x25, [x12, #-128]
-    __ ldnp(r27, r22, Address(r17, -176));             //       ldnp    x27, x22, [x17, #-176]
+// SpecialCases
+    __ ccmn(zr, zr, 3u, Assembler::LE);                //        ccmn        xzr, xzr, #3, LE
+    __ ccmnw(zr, zr, 5u, Assembler::EQ);               //        ccmn        wzr, wzr, #5, EQ
+    __ ccmp(zr, 1, 4u, Assembler::NE);                 //        ccmp        xzr, 1, #4, NE
+    __ ccmpw(zr, 2, 2, Assembler::GT);                 //        ccmp        wzr, 2, #2, GT
+    __ extr(zr, zr, zr, 0);                            //        extr        xzr, xzr, xzr, 0
+    __ stlxp(r0, zr, zr, sp);                          //        stlxp        w0, xzr, xzr, [sp]
+    __ stlxpw(r2, zr, zr, r3);                         //        stlxp        w2, wzr, wzr, [x3]
+    __ stxp(r4, zr, zr, r5);                           //        stxp        w4, xzr, xzr, [x5]
+    __ stxpw(r6, zr, zr, sp);                          //        stxp        w6, wzr, wzr, [sp]
+    __ dup(v0, __ T16B, zr);                           //        dup        v0.16b, wzr
+    __ mov(v1, __ T1D, 0, zr);                         //        mov        v1.d[0], xzr
+    __ mov(v1, __ T2S, 1, zr);                         //        mov        v1.s[1], wzr
+    __ mov(v1, __ T4H, 2, zr);                         //        mov        v1.h[2], wzr
+    __ mov(v1, __ T8B, 3, zr);                         //        mov        v1.b[3], wzr
+    __ ld1(v31, v0, __ T2D, Address(__ post(r1, r0))); //        ld1        {v31.2d, v0.2d}, [x1], x0
 
 // FloatImmediateOp
-    __ fmovd(v0, 2.0);                                 //       fmov d0, #2.0
-    __ fmovd(v0, 2.125);                               //       fmov d0, #2.125
-    __ fmovd(v0, 4.0);                                 //       fmov d0, #4.0
-    __ fmovd(v0, 4.25);                                //       fmov d0, #4.25
-    __ fmovd(v0, 8.0);                                 //       fmov d0, #8.0
-    __ fmovd(v0, 8.5);                                 //       fmov d0, #8.5
-    __ fmovd(v0, 16.0);                                //       fmov d0, #16.0
-    __ fmovd(v0, 17.0);                                //       fmov d0, #17.0
-    __ fmovd(v0, 0.125);                               //       fmov d0, #0.125
-    __ fmovd(v0, 0.1328125);                           //       fmov d0, #0.1328125
-    __ fmovd(v0, 0.25);                                //       fmov d0, #0.25
-    __ fmovd(v0, 0.265625);                            //       fmov d0, #0.265625
-    __ fmovd(v0, 0.5);                                 //       fmov d0, #0.5
-    __ fmovd(v0, 0.53125);                             //       fmov d0, #0.53125
-    __ fmovd(v0, 1.0);                                 //       fmov d0, #1.0
-    __ fmovd(v0, 1.0625);                              //       fmov d0, #1.0625
-    __ fmovd(v0, -2.0);                                //       fmov d0, #-2.0
-    __ fmovd(v0, -2.125);                              //       fmov d0, #-2.125
-    __ fmovd(v0, -4.0);                                //       fmov d0, #-4.0
-    __ fmovd(v0, -4.25);                               //       fmov d0, #-4.25
-    __ fmovd(v0, -8.0);                                //       fmov d0, #-8.0
-    __ fmovd(v0, -8.5);                                //       fmov d0, #-8.5
-    __ fmovd(v0, -16.0);                               //       fmov d0, #-16.0
-    __ fmovd(v0, -17.0);                               //       fmov d0, #-17.0
-    __ fmovd(v0, -0.125);                              //       fmov d0, #-0.125
-    __ fmovd(v0, -0.1328125);                          //       fmov d0, #-0.1328125
-    __ fmovd(v0, -0.25);                               //       fmov d0, #-0.25
-    __ fmovd(v0, -0.265625);                           //       fmov d0, #-0.265625
-    __ fmovd(v0, -0.5);                                //       fmov d0, #-0.5
-    __ fmovd(v0, -0.53125);                            //       fmov d0, #-0.53125
-    __ fmovd(v0, -1.0);                                //       fmov d0, #-1.0
-    __ fmovd(v0, -1.0625);                             //       fmov d0, #-1.0625
+    __ fmovd(v0, 2.0);                                 //        fmov d0, #2.0
+    __ fmovd(v0, 2.125);                               //        fmov d0, #2.125
+    __ fmovd(v0, 4.0);                                 //        fmov d0, #4.0
+    __ fmovd(v0, 4.25);                                //        fmov d0, #4.25
+    __ fmovd(v0, 8.0);                                 //        fmov d0, #8.0
+    __ fmovd(v0, 8.5);                                 //        fmov d0, #8.5
+    __ fmovd(v0, 16.0);                                //        fmov d0, #16.0
+    __ fmovd(v0, 17.0);                                //        fmov d0, #17.0
+    __ fmovd(v0, 0.125);                               //        fmov d0, #0.125
+    __ fmovd(v0, 0.1328125);                           //        fmov d0, #0.1328125
+    __ fmovd(v0, 0.25);                                //        fmov d0, #0.25
+    __ fmovd(v0, 0.265625);                            //        fmov d0, #0.265625
+    __ fmovd(v0, 0.5);                                 //        fmov d0, #0.5
+    __ fmovd(v0, 0.53125);                             //        fmov d0, #0.53125
+    __ fmovd(v0, 1.0);                                 //        fmov d0, #1.0
+    __ fmovd(v0, 1.0625);                              //        fmov d0, #1.0625
+    __ fmovd(v0, -2.0);                                //        fmov d0, #-2.0
+    __ fmovd(v0, -2.125);                              //        fmov d0, #-2.125
+    __ fmovd(v0, -4.0);                                //        fmov d0, #-4.0
+    __ fmovd(v0, -4.25);                               //        fmov d0, #-4.25
+    __ fmovd(v0, -8.0);                                //        fmov d0, #-8.0
+    __ fmovd(v0, -8.5);                                //        fmov d0, #-8.5
+    __ fmovd(v0, -16.0);                               //        fmov d0, #-16.0
+    __ fmovd(v0, -17.0);                               //        fmov d0, #-17.0
+    __ fmovd(v0, -0.125);                              //        fmov d0, #-0.125
+    __ fmovd(v0, -0.1328125);                          //        fmov d0, #-0.1328125
+    __ fmovd(v0, -0.25);                               //        fmov d0, #-0.25
+    __ fmovd(v0, -0.265625);                           //        fmov d0, #-0.265625
+    __ fmovd(v0, -0.5);                                //        fmov d0, #-0.5
+    __ fmovd(v0, -0.53125);                            //        fmov d0, #-0.53125
+    __ fmovd(v0, -1.0);                                //        fmov d0, #-1.0
+    __ fmovd(v0, -1.0625);                             //        fmov d0, #-1.0625
+
+// LSEOp
+    __ swp(Assembler::xword, r21, r5, r24);            //        swp        x21, x5, [x24]
+    __ ldadd(Assembler::xword, r13, r13, r15);         //        ldadd        x13, x13, [x15]
+    __ ldbic(Assembler::xword, r22, r19, r26);         //        ldclr        x22, x19, [x26]
+    __ ldeor(Assembler::xword, r25, r10, r26);         //        ldeor        x25, x10, [x26]
+    __ ldorr(Assembler::xword, r5, r27, r15);          //        ldset        x5, x27, [x15]
+    __ ldsmin(Assembler::xword, r19, r5, r11);         //        ldsmin        x19, x5, [x11]
+    __ ldsmax(Assembler::xword, r26, r0, r4);          //        ldsmax        x26, x0, [x4]
+    __ ldumin(Assembler::xword, r22, r23, r30);        //        ldumin        x22, x23, [x30]
+    __ ldumax(Assembler::xword, r18, r28, r8);         //        ldumax        x18, x28, [x8]
+
+// LSEOp
+    __ swpa(Assembler::xword, r13, r29, r27);          //        swpa        x13, x29, [x27]
+    __ ldadda(Assembler::xword, r11, r5, r13);         //        ldadda        x11, x5, [x13]
+    __ ldbica(Assembler::xword, r1, r24, r21);         //        ldclra        x1, x24, [x21]
+    __ ldeora(Assembler::xword, r27, r17, r24);        //        ldeora        x27, x17, [x24]
+    __ ldorra(Assembler::xword, r18, r30, r5);         //        ldseta        x18, x30, [x5]
+    __ ldsmina(Assembler::xword, r7, r22, r25);        //        ldsmina        x7, x22, [x25]
+    __ ldsmaxa(Assembler::xword, r4, r26, r19);        //        ldsmaxa        x4, x26, [x19]
+    __ ldumina(Assembler::xword, r6, r30, r3);         //        ldumina        x6, x30, [x3]
+    __ ldumaxa(Assembler::xword, r24, r23, r5);        //        ldumaxa        x24, x23, [x5]
+
+// LSEOp
+    __ swpal(Assembler::xword, r24, r18, r28);         //        swpal        x24, x18, [x28]
+    __ ldaddal(Assembler::xword, r19, zr, r7);         //        ldaddal        x19, xzr, [x7]
+    __ ldbical(Assembler::xword, r13, r6, r28);        //        ldclral        x13, x6, [x28]
+    __ ldeoral(Assembler::xword, r8, r15, r21);        //        ldeoral        x8, x15, [x21]
+    __ ldorral(Assembler::xword, r2, r13, r1);         //        ldsetal        x2, x13, [x1]
+    __ ldsminal(Assembler::xword, r17, r29, r25);      //        ldsminal        x17, x29, [x25]
+    __ ldsmaxal(Assembler::xword, r25, r18, r14);      //        ldsmaxal        x25, x18, [x14]
+    __ lduminal(Assembler::xword, zr, r6, r27);        //        lduminal        xzr, x6, [x27]
+    __ ldumaxal(Assembler::xword, r16, r5, r15);       //        ldumaxal        x16, x5, [x15]
+
+// LSEOp
+    __ swpl(Assembler::xword, r11, r18, r3);           //        swpl        x11, x18, [x3]
+    __ ldaddl(Assembler::xword, r26, r20, r2);         //        ldaddl        x26, x20, [x2]
+    __ ldbicl(Assembler::xword, r11, r4, r11);         //        ldclrl        x11, x4, [x11]
+    __ ldeorl(Assembler::xword, r30, r19, r23);        //        ldeorl        x30, x19, [x23]
+    __ ldorrl(Assembler::xword, r3, r15, r14);         //        ldsetl        x3, x15, [x14]
+    __ ldsminl(Assembler::xword, r30, r22, r20);       //        ldsminl        x30, x22, [x20]
+    __ ldsmaxl(Assembler::xword, r7, r5, r24);         //        ldsmaxl        x7, x5, [x24]
+    __ lduminl(Assembler::xword, r23, r16, r15);       //        lduminl        x23, x16, [x15]
+    __ ldumaxl(Assembler::xword, r11, r19, r0);        //        ldumaxl        x11, x19, [x0]
+
+// LSEOp
+    __ swp(Assembler::word, r28, r28, r1);             //        swp        w28, w28, [x1]
+    __ ldadd(Assembler::word, r11, r21, r12);          //        ldadd        w11, w21, [x12]
+    __ ldbic(Assembler::word, r29, r0, r18);           //        ldclr        w29, w0, [x18]
+    __ ldeor(Assembler::word, r5, r0, r25);            //        ldeor        w5, w0, [x25]
+    __ ldorr(Assembler::word, r14, r0, r26);           //        ldset        w14, w0, [x26]
+    __ ldsmin(Assembler::word, r28, r18, r29);         //        ldsmin        w28, w18, [x29]
+    __ ldsmax(Assembler::word, r15, r1, r29);          //        ldsmax        w15, w1, [x29]
+    __ ldumin(Assembler::word, r8, r26, r28);          //        ldumin        w8, w26, [x28]
+    __ ldumax(Assembler::word, r17, r14, r4);          //        ldumax        w17, w14, [x4]
+
+// LSEOp
+    __ swpa(Assembler::word, r24, r25, r1);            //        swpa        w24, w25, [x1]
+    __ ldadda(Assembler::word, r10, r17, r17);         //        ldadda        w10, w17, [x17]
+    __ ldbica(Assembler::word, r29, r20, r21);         //        ldclra        w29, w20, [x21]
+    __ ldeora(Assembler::word, r29, r9, r12);          //        ldeora        w29, w9, [x12]
+    __ ldorra(Assembler::word, r11, r6, r5);           //        ldseta        w11, w6, [x5]
+    __ ldsmina(Assembler::word, r21, r7, r21);         //        ldsmina        w21, w7, [x21]
+    __ ldsmaxa(Assembler::word, r10, r23, r12);        //        ldsmaxa        w10, w23, [x12]
+    __ ldumina(Assembler::word, r21, r5, r10);         //        ldumina        w21, w5, [x10]
+    __ ldumaxa(Assembler::word, r30, r20, r18);        //        ldumaxa        w30, w20, [x18]
+
+// LSEOp
+    __ swpal(Assembler::word, r13, r23, r5);           //        swpal        w13, w23, [x5]
+    __ ldaddal(Assembler::word, r15, r24, r5);         //        ldaddal        w15, w24, [x5]
+    __ ldbical(Assembler::word, r9, r10, r25);         //        ldclral        w9, w10, [x25]
+    __ ldeoral(Assembler::word, r20, r17, r17);        //        ldeoral        w20, w17, [x17]
+    __ ldorral(Assembler::word, r12, r18, r30);        //        ldsetal        w12, w18, [x30]
+    __ ldsminal(Assembler::word, r3, r3, r25);         //        ldsminal        w3, w3, [x25]
+    __ ldsmaxal(Assembler::word, r26, r25, r10);       //        ldsmaxal        w26, w25, [x10]
+    __ lduminal(Assembler::word, r2, r11, sp);         //        lduminal        w2, w11, [sp]
+    __ ldumaxal(Assembler::word, r7, r2, r5);          //        ldumaxal        w7, w2, [x5]
+
+// LSEOp
+    __ swpl(Assembler::word, r0, r7, r20);             //        swpl        w0, w7, [x20]
+    __ ldaddl(Assembler::word, r5, zr, r2);            //        ldaddl        w5, wzr, [x2]
+    __ ldbicl(Assembler::word, r27, r25, r27);         //        ldclrl        w27, w25, [x27]
+    __ ldeorl(Assembler::word, r30, r24, r26);         //        ldeorl        w30, w24, [x26]
+    __ ldorrl(Assembler::word, r15, r2, r22);          //        ldsetl        w15, w2, [x22]
+    __ ldsminl(Assembler::word, r0, r3, sp);           //        ldsminl        w0, w3, [sp]
+    __ ldsmaxl(Assembler::word, r15, r20, r10);        //        ldsmaxl        w15, w20, [x10]
+    __ lduminl(Assembler::word, r22, r21, r14);        //        lduminl        w22, w21, [x14]
+    __ ldumaxl(Assembler::word, r6, r30, r2);          //        ldumaxl        w6, w30, [x2]
 
     __ bind(forth);
 
@@ -638,542 +769,681 @@
 Disassembly of section .text:
 
 0000000000000000 <back>:
-   0:   8b0772d3        add     x19, x22, x7, lsl #28
-   4:   cb4a3570        sub     x16, x11, x10, lsr #13
-   8:   ab9c09bb        adds    x27, x13, x28, asr #2
-   c:   eb9aa794        subs    x20, x28, x26, asr #41
-  10:   0b934e68        add     w8, w19, w19, asr #19
-  14:   4b0a3924        sub     w4, w9, w10, lsl #14
-  18:   2b1e3568        adds    w8, w11, w30, lsl #13
-  1c:   6b132720        subs    w0, w25, w19, lsl #9
-  20:   8a154c14        and     x20, x0, x21, lsl #19
-  24:   aa1445d5        orr     x21, x14, x20, lsl #17
-  28:   ca01cf99        eor     x25, x28, x1, lsl #51
-  2c:   ea8b3f6a        ands    x10, x27, x11, asr #15
-  30:   0a8c5cb9        and     w25, w5, w12, asr #23
-  34:   2a4a11d2        orr     w18, w14, w10, lsr #4
-  38:   4a855aa4        eor     w4, w21, w5, asr #22
-  3c:   6a857415        ands    w21, w0, w5, asr #29
-  40:   8aa697da        bic     x26, x30, x6, asr #37
-  44:   aa6d7423        orn     x3, x1, x13, lsr #29
-  48:   ca29bf80        eon     x0, x28, x9, lsl #47
-  4c:   ea3cb8bd        bics    x29, x5, x28, lsl #46
-  50:   0a675249        bic     w9, w18, w7, lsr #20
-  54:   2ab961ba        orn     w26, w13, w25, asr #24
-  58:   4a331899        eon     w25, w4, w19, lsl #6
-  5c:   6a646345        bics    w5, w26, w4, lsr #24
-  60:   11055267        add     w7, w19, #0x154
-  64:   31064408        adds    w8, w0, #0x191
-  68:   51028e9d        sub     w29, w20, #0xa3
-  6c:   710bdee8        subs    w8, w23, #0x2f7
-  70:   91082d81        add     x1, x12, #0x20b
-  74:   b106a962        adds    x2, x11, #0x1aa
-  78:   d10b33ae        sub     x14, x29, #0x2cc
-  7c:   f10918ab        subs    x11, x5, #0x246
-  80:   121102d7        and     w23, w22, #0x8000
-  84:   3204cd44        orr     w4, w10, #0xf0f0f0f0
-  88:   5204cf00        eor     w0, w24, #0xf0f0f0f0
-  8c:   72099fb3        ands    w19, w29, #0x7f807f80
-  90:   92729545        and     x5, x10, #0xfffffffffc000
-  94:   b20e37cc        orr     x12, x30, #0xfffc0000fffc0000
-  98:   d27c34be        eor     x30, x5, #0x3fff0
-  9c:   f27e4efa        ands    x26, x23, #0x3ffffc
-  a0:   14000000        b       a0 <back+0xa0>
-  a4:   17ffffd7        b       0 <back>
-  a8:   1400017f        b       6a4 <forth>
-  ac:   94000000        bl      ac <back+0xac>
-  b0:   97ffffd4        bl      0 <back>
-  b4:   9400017c        bl      6a4 <forth>
-  b8:   3400000c        cbz     w12, b8 <back+0xb8>
-  bc:   34fffa2c        cbz     w12, 0 <back>
-  c0:   34002f2c        cbz     w12, 6a4 <forth>
-  c4:   35000014        cbnz    w20, c4 <back+0xc4>
-  c8:   35fff9d4        cbnz    w20, 0 <back>
-  cc:   35002ed4        cbnz    w20, 6a4 <forth>
-  d0:   b400000c        cbz     x12, d0 <back+0xd0>
-  d4:   b4fff96c        cbz     x12, 0 <back>
-  d8:   b4002e6c        cbz     x12, 6a4 <forth>
-  dc:   b5000018        cbnz    x24, dc <back+0xdc>
-  e0:   b5fff918        cbnz    x24, 0 <back>
-  e4:   b5002e18        cbnz    x24, 6a4 <forth>
-  e8:   10000006        adr     x6, e8 <back+0xe8>
-  ec:   10fff8a6        adr     x6, 0 <back>
-  f0:   10002da6        adr     x6, 6a4 <forth>
-  f4:   90000015        adrp    x21, 0 <back>
-  f8:   36080001        tbz     w1, #1, f8 <back+0xf8>
-  fc:   360ff821        tbz     w1, #1, 0 <back>
- 100:   36082d21        tbz     w1, #1, 6a4 <forth>
- 104:   37480008        tbnz    w8, #9, 104 <back+0x104>
- 108:   374ff7c8        tbnz    w8, #9, 0 <back>
- 10c:   37482cc8        tbnz    w8, #9, 6a4 <forth>
- 110:   128b50ec        movn    w12, #0x5a87
- 114:   52a9ff8b        movz    w11, #0x4ffc, lsl #16
- 118:   7281d095        movk    w21, #0xe84
- 11c:   92edfebd        movn    x29, #0x6ff5, lsl #48
- 120:   d28361e3        movz    x3, #0x1b0f
- 124:   f2a4cc96        movk    x22, #0x2664, lsl #16
- 128:   9346590c        sbfx    x12, x8, #6, #17
- 12c:   33194f33        bfi     w19, w25, #7, #20
- 130:   531d3d89        ubfiz   w9, w12, #3, #16
- 134:   9350433c        sbfx    x28, x25, #16, #1
- 138:   b34464ac        bfxil   x12, x5, #4, #22
- 13c:   d3462140        ubfx    x0, x10, #6, #3
- 140:   139a61a4        extr    w4, w13, w26, #24
- 144:   93d87fd7        extr    x23, x30, x24, #31
- 148:   54000000        b.eq    148 <back+0x148>
- 14c:   54fff5a0        b.eq    0 <back>
- 150:   54002aa0        b.eq    6a4 <forth>
- 154:   54000001        b.ne    154 <back+0x154>
- 158:   54fff541        b.ne    0 <back>
- 15c:   54002a41        b.ne    6a4 <forth>
- 160:   54000002        b.cs    160 <back+0x160>
- 164:   54fff4e2        b.cs    0 <back>
- 168:   540029e2        b.cs    6a4 <forth>
- 16c:   54000002        b.cs    16c <back+0x16c>
- 170:   54fff482        b.cs    0 <back>
- 174:   54002982        b.cs    6a4 <forth>
- 178:   54000003        b.cc    178 <back+0x178>
- 17c:   54fff423        b.cc    0 <back>
- 180:   54002923        b.cc    6a4 <forth>
- 184:   54000003        b.cc    184 <back+0x184>
- 188:   54fff3c3        b.cc    0 <back>
- 18c:   540028c3        b.cc    6a4 <forth>
- 190:   54000004        b.mi    190 <back+0x190>
- 194:   54fff364        b.mi    0 <back>
- 198:   54002864        b.mi    6a4 <forth>
- 19c:   54000005        b.pl    19c <back+0x19c>
- 1a0:   54fff305        b.pl    0 <back>
- 1a4:   54002805        b.pl    6a4 <forth>
- 1a8:   54000006        b.vs    1a8 <back+0x1a8>
- 1ac:   54fff2a6        b.vs    0 <back>
- 1b0:   540027a6        b.vs    6a4 <forth>
- 1b4:   54000007        b.vc    1b4 <back+0x1b4>
- 1b8:   54fff247        b.vc    0 <back>
- 1bc:   54002747        b.vc    6a4 <forth>
- 1c0:   54000008        b.hi    1c0 <back+0x1c0>
- 1c4:   54fff1e8        b.hi    0 <back>
- 1c8:   540026e8        b.hi    6a4 <forth>
- 1cc:   54000009        b.ls    1cc <back+0x1cc>
- 1d0:   54fff189        b.ls    0 <back>
- 1d4:   54002689        b.ls    6a4 <forth>
- 1d8:   5400000a        b.ge    1d8 <back+0x1d8>
- 1dc:   54fff12a        b.ge    0 <back>
- 1e0:   5400262a        b.ge    6a4 <forth>
- 1e4:   5400000b        b.lt    1e4 <back+0x1e4>
- 1e8:   54fff0cb        b.lt    0 <back>
- 1ec:   540025cb        b.lt    6a4 <forth>
- 1f0:   5400000c        b.gt    1f0 <back+0x1f0>
- 1f4:   54fff06c        b.gt    0 <back>
- 1f8:   5400256c        b.gt    6a4 <forth>
- 1fc:   5400000d        b.le    1fc <back+0x1fc>
- 200:   54fff00d        b.le    0 <back>
- 204:   5400250d        b.le    6a4 <forth>
- 208:   5400000e        b.al    208 <back+0x208>
- 20c:   54ffefae        b.al    0 <back>
- 210:   540024ae        b.al    6a4 <forth>
- 214:   5400000f        b.nv    214 <back+0x214>
- 218:   54ffef4f        b.nv    0 <back>
- 21c:   5400244f        b.nv    6a4 <forth>
- 220:   d4063721        svc     #0x31b9
- 224:   d4035082        hvc     #0x1a84
- 228:   d400bfe3        smc     #0x5ff
- 22c:   d4282fc0        brk     #0x417e
- 230:   d444c320        hlt     #0x2619
- 234:   d503201f        nop
- 238:   d69f03e0        eret
- 23c:   d6bf03e0        drps
- 240:   d5033fdf        isb
- 244:   d5033f9f        dsb     sy
- 248:   d5033abf        dmb     ishst
- 24c:   d61f0040        br      x2
- 250:   d63f00a0        blr     x5
- 254:   c8147c55        stxr    w20, x21, [x2]
- 258:   c805fcfd        stlxr   w5, x29, [x7]
- 25c:   c85f7e05        ldxr    x5, [x16]
- 260:   c85fffbb        ldaxr   x27, [x29]
- 264:   c89fffa0        stlr    x0, [x29]
- 268:   c8dfff95        ldar    x21, [x28]
- 26c:   88157cf8        stxr    w21, w24, [x7]
- 270:   8815ff9a        stlxr   w21, w26, [x28]
- 274:   885f7cd5        ldxr    w21, [x6]
- 278:   885fffcf        ldaxr   w15, [x30]
- 27c:   889ffc73        stlr    w19, [x3]
- 280:   88dffc56        ldar    w22, [x2]
- 284:   48127c0f        stxrh   w18, w15, [x0]
- 288:   480bff85        stlxrh  w11, w5, [x28]
- 28c:   485f7cdd        ldxrh   w29, [x6]
- 290:   485ffcf2        ldaxrh  w18, [x7]
- 294:   489fff99        stlrh   w25, [x28]
- 298:   48dffe62        ldarh   w2, [x19]
- 29c:   080a7c3e        stxrb   w10, w30, [x1]
- 2a0:   0814fed5        stlxrb  w20, w21, [x22]
- 2a4:   085f7c59        ldxrb   w25, [x2]
- 2a8:   085ffcb8        ldaxrb  w24, [x5]
- 2ac:   089ffc70        stlrb   w16, [x3]
- 2b0:   08dfffb6        ldarb   w22, [x29]
- 2b4:   c87f0a68        ldxp    x8, x2, [x19]
- 2b8:   c87fcdc7        ldaxp   x7, x19, [x14]
- 2bc:   c82870bb        stxp    w8, x27, x28, [x5]
- 2c0:   c825b8c8        stlxp   w5, x8, x14, [x6]
- 2c4:   887f12d9        ldxp    w25, w4, [x22]
- 2c8:   887fb9ed        ldaxp   w13, w14, [x15]
- 2cc:   8834215a        stxp    w20, w26, w8, [x10]
- 2d0:   8837ca52        stlxp   w23, w18, w18, [x18]
- 2d4:   f806317e        str     x30, [x11,#99]
- 2d8:   b81b3337        str     w23, [x25,#-77]
- 2dc:   39000dc2        strb    w2, [x14,#3]
- 2e0:   78005149        strh    w9, [x10,#5]
- 2e4:   f84391f4        ldr     x20, [x15,#57]
- 2e8:   b85b220c        ldr     w12, [x16,#-78]
- 2ec:   385fd356        ldrb    w22, [x26,#-3]
- 2f0:   785d127e        ldrh    w30, [x19,#-47]
- 2f4:   389f4149        ldrsb   x9, [x10,#-12]
- 2f8:   79801e3c        ldrsh   x28, [x17,#14]
- 2fc:   79c014a3        ldrsh   w3, [x5,#10]
- 300:   b89a5231        ldrsw   x17, [x17,#-91]
- 304:   fc5ef282        ldr     d2, [x20,#-17]
- 308:   bc5f60f6        ldr     s22, [x7,#-10]
- 30c:   fc12125e        str     d30, [x18,#-223]
- 310:   bc0152cd        str     s13, [x22,#21]
- 314:   f8190e49        str     x9, [x18,#-112]!
- 318:   b800befd        str     w29, [x23,#11]!
- 31c:   381ffd92        strb    w18, [x12,#-1]!
- 320:   781e9e90        strh    w16, [x20,#-23]!
- 324:   f8409fa3        ldr     x3, [x29,#9]!
- 328:   b8413c79        ldr     w25, [x3,#19]!
- 32c:   385fffa1        ldrb    w1, [x29,#-1]!
- 330:   785c7fa8        ldrh    w8, [x29,#-57]!
- 334:   389f3dc5        ldrsb   x5, [x14,#-13]!
- 338:   78801f6a        ldrsh   x10, [x27,#1]!
- 33c:   78c19d4b        ldrsh   w11, [x10,#25]!
- 340:   b89a4ec4        ldrsw   x4, [x22,#-92]!
- 344:   fc408eeb        ldr     d11, [x23,#8]!
- 348:   bc436e79        ldr     s25, [x19,#54]!
- 34c:   fc152ce1        str     d1, [x7,#-174]!
- 350:   bc036f28        str     s8, [x25,#54]!
- 354:   f8025565        str     x5, [x11],#37
- 358:   b80135f8        str     w24, [x15],#19
- 35c:   381ff74f        strb    w15, [x26],#-1
- 360:   781fa652        strh    w18, [x18],#-6
- 364:   f851a447        ldr     x7, [x2],#-230
- 368:   b85e557b        ldr     w27, [x11],#-27
- 36c:   385e7472        ldrb    w18, [x3],#-25
- 370:   785e070a        ldrh    w10, [x24],#-32
- 374:   38804556        ldrsb   x22, [x10],#4
- 378:   78819591        ldrsh   x17, [x12],#25
- 37c:   78dc24e8        ldrsh   w8, [x7],#-62
- 380:   b89cd6d7        ldrsw   x23, [x22],#-51
- 384:   fc430738        ldr     d24, [x25],#48
- 388:   bc5f6595        ldr     s21, [x12],#-10
- 38c:   fc1225b2        str     d18, [x13],#-222
- 390:   bc1d7430        str     s16, [x1],#-41
- 394:   f82fcac2        str     x2, [x22,w15,sxtw]
- 398:   b83d6a02        str     w2, [x16,x29]
- 39c:   382e5a54        strb    w20, [x18,w14,uxtw #0]
- 3a0:   7834fa66        strh    w6, [x19,x20,sxtx #1]
- 3a4:   f86ecbae        ldr     x14, [x29,w14,sxtw]
- 3a8:   b86cda90        ldr     w16, [x20,w12,sxtw #2]
- 3ac:   3860d989        ldrb    w9, [x12,w0,sxtw #0]
- 3b0:   78637a2c        ldrh    w12, [x17,x3,lsl #1]
- 3b4:   38a3fa22        ldrsb   x2, [x17,x3,sxtx #0]
- 3b8:   78b15827        ldrsh   x7, [x1,w17,uxtw #1]
- 3bc:   78f2d9f9        ldrsh   w25, [x15,w18,sxtw #1]
- 3c0:   b8ac6ab7        ldrsw   x23, [x21,x12]
- 3c4:   fc6879a5        ldr     d5, [x13,x8,lsl #3]
- 3c8:   bc767943        ldr     s3, [x10,x22,lsl #2]
- 3cc:   fc3bc84e        str     d14, [x2,w27,sxtw]
- 3d0:   bc3968d4        str     s20, [x6,x25]
- 3d4:   f91fc0fe        str     x30, [x7,#16256]
- 3d8:   b91da50f        str     w15, [x8,#7588]
- 3dc:   391d280b        strb    w11, [x0,#1866]
- 3e0:   791d2e23        strh    w3, [x17,#3734]
- 3e4:   f95bc8e2        ldr     x2, [x7,#14224]
- 3e8:   b95ce525        ldr     w5, [x9,#7396]
- 3ec:   395ae53c        ldrb    w28, [x9,#1721]
- 3f0:   795c9282        ldrh    w2, [x20,#3656]
- 3f4:   399d7dd6        ldrsb   x22, [x14,#1887]
- 3f8:   799fe008        ldrsh   x8, [x0,#4080]
- 3fc:   79de9bc0        ldrsh   w0, [x30,#3916]
- 400:   b99aae78        ldrsw   x24, [x19,#6828]
- 404:   fd597598        ldr     d24, [x12,#13032]
- 408:   bd5d1d08        ldr     s8, [x8,#7452]
- 40c:   fd1f3dea        str     d10, [x15,#15992]
- 410:   bd1a227a        str     s26, [x19,#6688]
- 414:   5800148a        ldr     x10, 6a4 <forth>
- 418:   18000003        ldr     w3, 418 <back+0x418>
- 41c:   f88092e0        prfm    pldl1keep, [x23,#9]
- 420:   d8ffdf00        prfm    pldl1keep, 0 <back>
- 424:   f8a84860        prfm    pldl1keep, [x3,w8,uxtw]
- 428:   f99d7560        prfm    pldl1keep, [x11,#15080]
- 42c:   1a1c012d        adc     w13, w9, w28
- 430:   3a1c027b        adcs    w27, w19, w28
- 434:   5a060253        sbc     w19, w18, w6
- 438:   7a03028e        sbcs    w14, w20, w3
- 43c:   9a0801d0        adc     x16, x14, x8
- 440:   ba0803a0        adcs    x0, x29, x8
- 444:   da140308        sbc     x8, x24, x20
- 448:   fa00038c        sbcs    x12, x28, x0
- 44c:   0b3010d7        add     w23, w6, w16, uxtb #4
- 450:   2b37ab39        adds    w25, w25, w23, sxth #2
- 454:   cb2466da        sub     x26, x22, x4, uxtx #1
- 458:   6b33efb1        subs    w17, w29, w19, sxtx #3
- 45c:   8b350fcb        add     x11, x30, w21, uxtb #3
- 460:   ab208a70        adds    x16, x19, w0, sxtb #2
- 464:   cb39e52b        sub     x11, x9, x25, sxtx #1
- 468:   eb2c9291        subs    x17, x20, w12, sxtb #4
- 46c:   3a4bd1a3        ccmn    w13, w11, #0x3, le
- 470:   7a4c81a2        ccmp    w13, w12, #0x2, hi
- 474:   ba42106c        ccmn    x3, x2, #0xc, ne
- 478:   fa5560e3        ccmp    x7, x21, #0x3, vs
- 47c:   3a4e3844        ccmn    w2, #0xe, #0x4, cc
- 480:   7a515a26        ccmp    w17, #0x11, #0x6, pl
- 484:   ba4c2940        ccmn    x10, #0xc, #0x0, cs
- 488:   fa52aaae        ccmp    x21, #0x12, #0xe, ge
- 48c:   1a8cc1b5        csel    w21, w13, w12, gt
- 490:   1a8f976a        csinc   w10, w27, w15, ls
- 494:   5a8981a0        csinv   w0, w13, w9, hi
- 498:   5a9a6492        csneg   w18, w4, w26, vs
- 49c:   9a8793ac        csel    x12, x29, x7, ls
- 4a0:   9a9474e6        csinc   x6, x7, x20, vc
- 4a4:   da83d2b6        csinv   x22, x21, x3, le
- 4a8:   da9b9593        csneg   x19, x12, x27, ls
- 4ac:   5ac00200        rbit    w0, w16
- 4b0:   5ac006f1        rev16   w17, w23
- 4b4:   5ac009d1        rev     w17, w14
- 4b8:   5ac013d8        clz     w24, w30
- 4bc:   5ac016d8        cls     w24, w22
- 4c0:   dac00223        rbit    x3, x17
- 4c4:   dac005ac        rev16   x12, x13
- 4c8:   dac00ac9        rev32   x9, x22
- 4cc:   dac00c00        rev     x0, x0
- 4d0:   dac01205        clz     x5, x16
- 4d4:   dac016d9        cls     x25, x22
- 4d8:   1ac0089d        udiv    w29, w4, w0
- 4dc:   1add0fa0        sdiv    w0, w29, w29
- 4e0:   1ad52225        lsl     w5, w17, w21
- 4e4:   1ad22529        lsr     w9, w9, w18
- 4e8:   1ac82b61        asr     w1, w27, w8
- 4ec:   1acd2e92        ror     w18, w20, w13
- 4f0:   9acc0b28        udiv    x8, x25, x12
- 4f4:   9adc0ca7        sdiv    x7, x5, x28
- 4f8:   9adb2225        lsl     x5, x17, x27
- 4fc:   9ad42757        lsr     x23, x26, x20
- 500:   9adc291c        asr     x28, x8, x28
- 504:   9ac42fa3        ror     x3, x29, x4
- 508:   1b1a55d1        madd    w17, w14, w26, w21
- 50c:   1b0bafc1        msub    w1, w30, w11, w11
- 510:   9b067221        madd    x1, x17, x6, x28
- 514:   9b1ea0de        msub    x30, x6, x30, x8
- 518:   9b2e20d5        smaddl  x21, w6, w14, x8
- 51c:   9b38cd4a        smsubl  x10, w10, w24, x19
- 520:   9bae6254        umaddl  x20, w18, w14, x24
- 524:   9ba59452        umsubl  x18, w2, w5, x5
- 528:   1e2d0a48        fmul    s8, s18, s13
- 52c:   1e3c19c2        fdiv    s2, s14, s28
- 530:   1e3c298f        fadd    s15, s12, s28
- 534:   1e213980        fsub    s0, s12, s1
- 538:   1e240baf        fmul    s15, s29, s4
- 53c:   1e77082c        fmul    d12, d1, d23
- 540:   1e72191b        fdiv    d27, d8, d18
- 544:   1e6b2a97        fadd    d23, d20, d11
- 548:   1e723988        fsub    d8, d12, d18
- 54c:   1e770b1a        fmul    d26, d24, d23
- 550:   1f0d66f5        fmadd   s21, s23, s13, s25
- 554:   1f01b956        fmsub   s22, s10, s1, s14
- 558:   1f227a8e        fnmadd  s14, s20, s2, s30
- 55c:   1f365ba7        fnmadd  s7, s29, s22, s22
- 560:   1f4f14ad        fmadd   d13, d5, d15, d5
- 564:   1f45a98e        fmsub   d14, d12, d5, d10
- 568:   1f60066a        fnmadd  d10, d19, d0, d1
- 56c:   1f620054        fnmadd  d20, d2, d2, d0
- 570:   1e204139        fmov    s25, s9
- 574:   1e20c094        fabs    s20, s4
- 578:   1e214363        fneg    s3, s27
- 57c:   1e21c041        fsqrt   s1, s2
- 580:   1e22c01e        fcvt    d30, s0
- 584:   1e60408c        fmov    d12, d4
- 588:   1e60c361        fabs    d1, d27
- 58c:   1e6142c8        fneg    d8, d22
- 590:   1e61c16b        fsqrt   d11, d11
- 594:   1e624396        fcvt    s22, d28
- 598:   1e3802dc        fcvtzs  w28, s22
- 59c:   9e380374        fcvtzs  x20, s27
- 5a0:   1e78000e        fcvtzs  w14, d0
- 5a4:   9e78017a        fcvtzs  x26, d11
- 5a8:   1e2202dc        scvtf   s28, w22
- 5ac:   9e220150        scvtf   s16, x10
- 5b0:   1e6202a8        scvtf   d8, w21
- 5b4:   9e620395        scvtf   d21, x28
- 5b8:   1e260318        fmov    w24, s24
- 5bc:   9e660268        fmov    x8, d19
- 5c0:   1e270188        fmov    s8, w12
- 5c4:   9e6700e6        fmov    d6, x7
- 5c8:   1e3023c0        fcmp    s30, s16
- 5cc:   1e6b2320        fcmp    d25, d11
- 5d0:   1e202168        fcmp    s11, #0.0
- 5d4:   1e602168        fcmp    d11, #0.0
- 5d8:   2910323d        stp     w29, w12, [x17,#128]
- 5dc:   297449d6        ldp     w22, w18, [x14,#-96]
- 5e0:   6948402b        ldpsw   x11, x16, [x1,#64]
- 5e4:   a9072f40        stp     x0, x11, [x26,#112]
- 5e8:   a9410747        ldp     x7, x1, [x26,#16]
- 5ec:   29801f0a        stp     w10, w7, [x24,#0]!
- 5f0:   29e07307        ldp     w7, w28, [x24,#-256]!
- 5f4:   69e272b9        ldpsw   x25, x28, [x21,#-240]!
- 5f8:   a9bf49d4        stp     x20, x18, [x14,#-16]!
- 5fc:   a9c529a8        ldp     x8, x10, [x13,#80]!
- 600:   28b0605a        stp     w26, w24, [x2],#-128
- 604:   28e866a2        ldp     w2, w25, [x21],#-192
- 608:   68ee0ab1        ldpsw   x17, x2, [x21],#-144
- 60c:   a886296c        stp     x12, x10, [x11],#96
- 610:   a8fe1a38        ldp     x24, x6, [x17],#-32
- 614:   282479c3        stnp    w3, w30, [x14,#-224]
- 618:   286e534f        ldnp    w15, w20, [x26,#-144]
- 61c:   a8386596        stnp    x22, x25, [x12,#-128]
- 620:   a8755a3b        ldnp    x27, x22, [x17,#-176]
- 624:   1e601000        fmov    d0, #2.000000000000000000e+00
- 628:   1e603000        fmov    d0, #2.125000000000000000e+00
- 62c:   1e621000        fmov    d0, #4.000000000000000000e+00
- 630:   1e623000        fmov    d0, #4.250000000000000000e+00
- 634:   1e641000        fmov    d0, #8.000000000000000000e+00
- 638:   1e643000        fmov    d0, #8.500000000000000000e+00
- 63c:   1e661000        fmov    d0, #1.600000000000000000e+01
- 640:   1e663000        fmov    d0, #1.700000000000000000e+01
- 644:   1e681000        fmov    d0, #1.250000000000000000e-01
- 648:   1e683000        fmov    d0, #1.328125000000000000e-01
- 64c:   1e6a1000        fmov    d0, #2.500000000000000000e-01
- 650:   1e6a3000        fmov    d0, #2.656250000000000000e-01
- 654:   1e6c1000        fmov    d0, #5.000000000000000000e-01
- 658:   1e6c3000        fmov    d0, #5.312500000000000000e-01
- 65c:   1e6e1000        fmov    d0, #1.000000000000000000e+00
- 660:   1e6e3000        fmov    d0, #1.062500000000000000e+00
- 664:   1e701000        fmov    d0, #-2.000000000000000000e+00
- 668:   1e703000        fmov    d0, #-2.125000000000000000e+00
- 66c:   1e721000        fmov    d0, #-4.000000000000000000e+00
- 670:   1e723000        fmov    d0, #-4.250000000000000000e+00
- 674:   1e741000        fmov    d0, #-8.000000000000000000e+00
- 678:   1e743000        fmov    d0, #-8.500000000000000000e+00
- 67c:   1e761000        fmov    d0, #-1.600000000000000000e+01
- 680:   1e763000        fmov    d0, #-1.700000000000000000e+01
- 684:   1e781000        fmov    d0, #-1.250000000000000000e-01
- 688:   1e783000        fmov    d0, #-1.328125000000000000e-01
- 68c:   1e7a1000        fmov    d0, #-2.500000000000000000e-01
- 690:   1e7a3000        fmov    d0, #-2.656250000000000000e-01
- 694:   1e7c1000        fmov    d0, #-5.000000000000000000e-01
- 698:   1e7c3000        fmov    d0, #-5.312500000000000000e-01
- 69c:   1e7e1000        fmov    d0, #-1.000000000000000000e+00
- 6a0:   1e7e3000        fmov    d0, #-1.062500000000000000e+00
+   0:        8b50798f         add        x15, x12, x16, lsr #30
+   4:        cb4381e1         sub        x1, x15, x3, lsr #32
+   8:        ab05372d         adds        x13, x25, x5, lsl #13
+   c:        eb864796         subs        x22, x28, x6, asr #17
+  10:        0b961920         add        w0, w9, w22, asr #6
+  14:        4b195473         sub        w19, w3, w25, lsl #21
+  18:        2b0b5264         adds        w4, w19, w11, lsl #20
+  1c:        6b9300f8         subs        w24, w7, w19, asr #0
+  20:        8a0bc0fe         and        x30, x7, x11, lsl #48
+  24:        aa0f3118         orr        x24, x8, x15, lsl #12
+  28:        ca170531         eor        x17, x9, x23, lsl #1
+  2c:        ea44dd6e         ands        x14, x11, x4, lsr #55
+  30:        0a4c44f3         and        w19, w7, w12, lsr #17
+  34:        2a8b7373         orr        w19, w27, w11, asr #28
+  38:        4a567c7e         eor        w30, w3, w22, lsr #31
+  3c:        6a9c0353         ands        w19, w26, w28, asr #0
+  40:        8a3accdd         bic        x29, x6, x26, lsl #51
+  44:        aa318f7a         orn        x26, x27, x17, lsl #35
+  48:        ca2e1495         eon        x21, x4, x14, lsl #5
+  4c:        eaa015e2         bics        x2, x15, x0, asr #5
+  50:        0a2274e2         bic        w2, w7, w2, lsl #29
+  54:        2a751598         orn        w24, w12, w21, lsr #5
+  58:        4a3309fe         eon        w30, w15, w19, lsl #2
+  5c:        6ab172fe         bics        w30, w23, w17, asr #28
+  60:        110a5284         add        w4, w20, #0x294
+  64:        310b1942         adds        w2, w10, #0x2c6
+  68:        5103d353         sub        w19, w26, #0xf4
+  6c:        710125bc         subs        w28, w13, #0x49
+  70:        910d7bc2         add        x2, x30, #0x35e
+  74:        b108fa1b         adds        x27, x16, #0x23e
+  78:        d1093536         sub        x22, x9, #0x24d
+  7c:        f10ae824         subs        x4, x1, #0x2ba
+  80:        120e667c         and        w28, w19, #0xfffc0fff
+  84:        321f6cbb         orr        w27, w5, #0x1ffffffe
+  88:        520f6a9e         eor        w30, w20, #0xfffe0fff
+  8c:        72136f56         ands        w22, w26, #0xffffe1ff
+  90:        927e4ce5         and        x5, x7, #0x3ffffc
+  94:        b278b4ed         orr        x13, x7, #0x3fffffffffff00
+  98:        d24c6527         eor        x7, x9, #0xfff0000000003fff
+  9c:        f2485803         ands        x3, x0, #0xff00000000007fff
+  a0:        14000000         b        a0 <back+0xa0>
+  a4:        17ffffd7         b        0 <back>
+  a8:        140001ee         b        860 <forth>
+  ac:        94000000         bl        ac <back+0xac>
+  b0:        97ffffd4         bl        0 <back>
+  b4:        940001eb         bl        860 <forth>
+  b8:        34000010         cbz        w16, b8 <back+0xb8>
+  bc:        34fffa30         cbz        w16, 0 <back>
+  c0:        34003d10         cbz        w16, 860 <forth>
+  c4:        35000013         cbnz        w19, c4 <back+0xc4>
+  c8:        35fff9d3         cbnz        w19, 0 <back>
+  cc:        35003cb3         cbnz        w19, 860 <forth>
+  d0:        b4000005         cbz        x5, d0 <back+0xd0>
+  d4:        b4fff965         cbz        x5, 0 <back>
+  d8:        b4003c45         cbz        x5, 860 <forth>
+  dc:        b5000004         cbnz        x4, dc <back+0xdc>
+  e0:        b5fff904         cbnz        x4, 0 <back>
+  e4:        b5003be4         cbnz        x4, 860 <forth>
+  e8:        1000001b         adr        x27, e8 <back+0xe8>
+  ec:        10fff8bb         adr        x27, 0 <back>
+  f0:        10003b9b         adr        x27, 860 <forth>
+  f4:        90000010         adrp        x16, 0 <back>
+  f8:        3640001c         tbz        w28, #8, f8 <back+0xf8>
+  fc:        3647f83c         tbz        w28, #8, 0 <back>
+ 100:        36403b1c         tbz        w28, #8, 860 <forth>
+ 104:        37080001         tbnz        w1, #1, 104 <back+0x104>
+ 108:        370ff7c1         tbnz        w1, #1, 0 <back>
+ 10c:        37083aa1         tbnz        w1, #1, 860 <forth>
+ 110:        12a437f4         mov        w20, #0xde40ffff                    // #-566165505
+ 114:        528c9d67         mov        w7, #0x64eb                        // #25835
+ 118:        72838bb1         movk        w17, #0x1c5d
+ 11c:        92c1062e         mov        x14, #0xfffff7ceffffffff            // #-9006546419713
+ 120:        d287da49         mov        x9, #0x3ed2                        // #16082
+ 124:        f2a6d153         movk        x19, #0x368a, lsl #16
+ 128:        93465ac9         sbfx        x9, x22, #6, #17
+ 12c:        330b0013         bfi        w19, w0, #21, #1
+ 130:        530b4e6a         ubfx        w10, w19, #11, #9
+ 134:        934545e4         sbfx        x4, x15, #5, #13
+ 138:        b35370a3         bfxil        x3, x5, #19, #10
+ 13c:        d3510b8c         ubfiz        x12, x28, #47, #3
+ 140:        13960c0f         extr        w15, w0, w22, #3
+ 144:        93ceddc6         ror        x6, x14, #55
+ 148:        54000000         b.eq        148 <back+0x148>  // b.none
+ 14c:        54fff5a0         b.eq        0 <back>  // b.none
+ 150:        54003880         b.eq        860 <forth>  // b.none
+ 154:        54000001         b.ne        154 <back+0x154>  // b.any
+ 158:        54fff541         b.ne        0 <back>  // b.any
+ 15c:        54003821         b.ne        860 <forth>  // b.any
+ 160:        54000002         b.cs        160 <back+0x160>  // b.hs, b.nlast
+ 164:        54fff4e2         b.cs        0 <back>  // b.hs, b.nlast
+ 168:        540037c2         b.cs        860 <forth>  // b.hs, b.nlast
+ 16c:        54000002         b.cs        16c <back+0x16c>  // b.hs, b.nlast
+ 170:        54fff482         b.cs        0 <back>  // b.hs, b.nlast
+ 174:        54003762         b.cs        860 <forth>  // b.hs, b.nlast
+ 178:        54000003         b.cc        178 <back+0x178>  // b.lo, b.ul, b.last
+ 17c:        54fff423         b.cc        0 <back>  // b.lo, b.ul, b.last
+ 180:        54003703         b.cc        860 <forth>  // b.lo, b.ul, b.last
+ 184:        54000003         b.cc        184 <back+0x184>  // b.lo, b.ul, b.last
+ 188:        54fff3c3         b.cc        0 <back>  // b.lo, b.ul, b.last
+ 18c:        540036a3         b.cc        860 <forth>  // b.lo, b.ul, b.last
+ 190:        54000004         b.mi        190 <back+0x190>  // b.first
+ 194:        54fff364         b.mi        0 <back>  // b.first
+ 198:        54003644         b.mi        860 <forth>  // b.first
+ 19c:        54000005         b.pl        19c <back+0x19c>  // b.nfrst
+ 1a0:        54fff305         b.pl        0 <back>  // b.nfrst
+ 1a4:        540035e5         b.pl        860 <forth>  // b.nfrst
+ 1a8:        54000006         b.vs        1a8 <back+0x1a8>
+ 1ac:        54fff2a6         b.vs        0 <back>
+ 1b0:        54003586         b.vs        860 <forth>
+ 1b4:        54000007         b.vc        1b4 <back+0x1b4>
+ 1b8:        54fff247         b.vc        0 <back>
+ 1bc:        54003527         b.vc        860 <forth>
+ 1c0:        54000008         b.hi        1c0 <back+0x1c0>  // b.pmore
+ 1c4:        54fff1e8         b.hi        0 <back>  // b.pmore
+ 1c8:        540034c8         b.hi        860 <forth>  // b.pmore
+ 1cc:        54000009         b.ls        1cc <back+0x1cc>  // b.plast
+ 1d0:        54fff189         b.ls        0 <back>  // b.plast
+ 1d4:        54003469         b.ls        860 <forth>  // b.plast
+ 1d8:        5400000a         b.ge        1d8 <back+0x1d8>  // b.tcont
+ 1dc:        54fff12a         b.ge        0 <back>  // b.tcont
+ 1e0:        5400340a         b.ge        860 <forth>  // b.tcont
+ 1e4:        5400000b         b.lt        1e4 <back+0x1e4>  // b.tstop
+ 1e8:        54fff0cb         b.lt        0 <back>  // b.tstop
+ 1ec:        540033ab         b.lt        860 <forth>  // b.tstop
+ 1f0:        5400000c         b.gt        1f0 <back+0x1f0>
+ 1f4:        54fff06c         b.gt        0 <back>
+ 1f8:        5400334c         b.gt        860 <forth>
+ 1fc:        5400000d         b.le        1fc <back+0x1fc>
+ 200:        54fff00d         b.le        0 <back>
+ 204:        540032ed         b.le        860 <forth>
+ 208:        5400000e         b.al        208 <back+0x208>
+ 20c:        54ffefae         b.al        0 <back>
+ 210:        5400328e         b.al        860 <forth>
+ 214:        5400000f         b.nv        214 <back+0x214>
+ 218:        54ffef4f         b.nv        0 <back>
+ 21c:        5400322f         b.nv        860 <forth>
+ 220:        d40ac601         svc        #0x5630
+ 224:        d40042a2         hvc        #0x215
+ 228:        d404dac3         smc        #0x26d6
+ 22c:        d4224d40         brk        #0x126a
+ 230:        d44219c0         hlt        #0x10ce
+ 234:        d503201f         nop
+ 238:        d69f03e0         eret
+ 23c:        d6bf03e0         drps
+ 240:        d5033fdf         isb
+ 244:        d503339f         dsb        osh
+ 248:        d50335bf         dmb        nshld
+ 24c:        d61f0280         br        x20
+ 250:        d63f0040         blr        x2
+ 254:        c8127c17         stxr        w18, x23, [x0]
+ 258:        c81efec5         stlxr        w30, x5, [x22]
+ 25c:        c85f7d05         ldxr        x5, [x8]
+ 260:        c85ffe14         ldaxr        x20, [x16]
+ 264:        c89ffd66         stlr        x6, [x11]
+ 268:        c8dfff66         ldar        x6, [x27]
+ 26c:        880a7cb1         stxr        w10, w17, [x5]
+ 270:        8816fd89         stlxr        w22, w9, [x12]
+ 274:        885f7d1b         ldxr        w27, [x8]
+ 278:        885ffc57         ldaxr        w23, [x2]
+ 27c:        889fffba         stlr        w26, [x29]
+ 280:        88dffd4d         ldar        w13, [x10]
+ 284:        48197f7c         stxrh        w25, w28, [x27]
+ 288:        481dfd96         stlxrh        w29, w22, [x12]
+ 28c:        485f7f96         ldxrh        w22, [x28]
+ 290:        485fffc3         ldaxrh        w3, [x30]
+ 294:        489ffdf8         stlrh        w24, [x15]
+ 298:        48dfff5b         ldarh        w27, [x26]
+ 29c:        080b7e6a         stxrb        w11, w10, [x19]
+ 2a0:        0817fedb         stlxrb        w23, w27, [x22]
+ 2a4:        085f7e18         ldxrb        w24, [x16]
+ 2a8:        085ffc38         ldaxrb        w24, [x1]
+ 2ac:        089fffa5         stlrb        w5, [x29]
+ 2b0:        08dffe18         ldarb        w24, [x16]
+ 2b4:        c87f6239         ldxp        x25, x24, [x17]
+ 2b8:        c87fb276         ldaxp        x22, x12, [x19]
+ 2bc:        c820573a         stxp        w0, x26, x21, [x25]
+ 2c0:        c821aca6         stlxp        w1, x6, x11, [x5]
+ 2c4:        887f388d         ldxp        w13, w14, [x4]
+ 2c8:        887f88d1         ldaxp        w17, w2, [x6]
+ 2cc:        882f2643         stxp        w15, w3, w9, [x18]
+ 2d0:        88329131         stlxp        w18, w17, w4, [x9]
+ 2d4:        f81cf2b7         stur        x23, [x21, #-49]
+ 2d8:        b803f055         stur        w21, [x2, #63]
+ 2dc:        39002f9b         strb        w27, [x28, #11]
+ 2e0:        781f31fd         sturh        w29, [x15, #-13]
+ 2e4:        f85d33ce         ldur        x14, [x30, #-45]
+ 2e8:        b843539d         ldur        w29, [x28, #53]
+ 2ec:        39401f54         ldrb        w20, [x26, #7]
+ 2f0:        785ce059         ldurh        w25, [x2, #-50]
+ 2f4:        389f1143         ldursb        x3, [x10, #-15]
+ 2f8:        788131ee         ldursh        x14, [x15, #19]
+ 2fc:        78dfb17d         ldursh        w29, [x11, #-5]
+ 300:        b89b90af         ldursw        x15, [x5, #-71]
+ 304:        fc403193         ldur        d19, [x12, #3]
+ 308:        bc42a36c         ldur        s12, [x27, #42]
+ 30c:        fc07d396         stur        d22, [x28, #125]
+ 310:        bc1ec1f8         stur        s24, [x15, #-20]
+ 314:        f81e8f88         str        x8, [x28, #-24]!
+ 318:        b8025de6         str        w6, [x15, #37]!
+ 31c:        38007c27         strb        w7, [x1, #7]!
+ 320:        7801ee20         strh        w0, [x17, #30]!
+ 324:        f8454fb9         ldr        x25, [x29, #84]!
+ 328:        b85cce9a         ldr        w26, [x20, #-52]!
+ 32c:        385e7fba         ldrb        w26, [x29, #-25]!
+ 330:        7841af24         ldrh        w4, [x25, #26]!
+ 334:        389ebd1c         ldrsb        x28, [x8, #-21]!
+ 338:        789fadd1         ldrsh        x17, [x14, #-6]!
+ 33c:        78c0aefc         ldrsh        w28, [x23, #10]!
+ 340:        b89c0f7e         ldrsw        x30, [x27, #-64]!
+ 344:        fc50efd4         ldr        d20, [x30, #-242]!
+ 348:        bc414f71         ldr        s17, [x27, #20]!
+ 34c:        fc011c67         str        d7, [x3, #17]!
+ 350:        bc1f0d6d         str        s13, [x11, #-16]!
+ 354:        f81c3526         str        x6, [x9], #-61
+ 358:        b81e34b0         str        w16, [x5], #-29
+ 35c:        3800f7bd         strb        w29, [x29], #15
+ 360:        78012684         strh        w4, [x20], #18
+ 364:        f842e653         ldr        x19, [x18], #46
+ 368:        b8417456         ldr        w22, [x2], #23
+ 36c:        385e2467         ldrb        w7, [x3], #-30
+ 370:        785e358b         ldrh        w11, [x12], #-29
+ 374:        389e34c8         ldrsb        x8, [x6], #-29
+ 378:        788046f8         ldrsh        x24, [x23], #4
+ 37c:        78c00611         ldrsh        w17, [x16], #0
+ 380:        b89f8680         ldrsw        x0, [x20], #-8
+ 384:        fc582454         ldr        d20, [x2], #-126
+ 388:        bc5987d3         ldr        s19, [x30], #-104
+ 38c:        fc076624         str        d4, [x17], #118
+ 390:        bc190675         str        s21, [x19], #-112
+ 394:        f833785a         str        x26, [x2, x19, lsl #3]
+ 398:        b82fd809         str        w9, [x0, w15, sxtw #2]
+ 39c:        3821799a         strb        w26, [x12, x1, lsl #0]
+ 3a0:        782a7975         strh        w21, [x11, x10, lsl #1]
+ 3a4:        f870eaf0         ldr        x16, [x23, x16, sxtx]
+ 3a8:        b871d96a         ldr        w10, [x11, w17, sxtw #2]
+ 3ac:        386b7aed         ldrb        w13, [x23, x11, lsl #0]
+ 3b0:        7875689b         ldrh        w27, [x4, x21]
+ 3b4:        38afd91a         ldrsb        x26, [x8, w15, sxtw #0]
+ 3b8:        78a2c955         ldrsh        x21, [x10, w2, sxtw]
+ 3bc:        78ee6bc8         ldrsh        w8, [x30, x14]
+ 3c0:        b8b4f9dd         ldrsw        x29, [x14, x20, sxtx #2]
+ 3c4:        fc76eb7e         ldr        d30, [x27, x22, sxtx]
+ 3c8:        bc76692d         ldr        s13, [x9, x22]
+ 3cc:        fc31db28         str        d8, [x25, w17, sxtw #3]
+ 3d0:        bc255b01         str        s1, [x24, w5, uxtw #2]
+ 3d4:        f91c52aa         str        x10, [x21, #14496]
+ 3d8:        b91c3fb2         str        w18, [x29, #7228]
+ 3dc:        391f8877         strb        w23, [x3, #2018]
+ 3e0:        791ac97c         strh        w28, [x11, #3428]
+ 3e4:        f95c1758         ldr        x24, [x26, #14376]
+ 3e8:        b95b3c55         ldr        w21, [x2, #6972]
+ 3ec:        395ce0a4         ldrb        w4, [x5, #1848]
+ 3f0:        795851ce         ldrh        w14, [x14, #3112]
+ 3f4:        399e9f64         ldrsb        x4, [x27, #1959]
+ 3f8:        79993764         ldrsh        x4, [x27, #3226]
+ 3fc:        79d9af8a         ldrsh        w10, [x28, #3286]
+ 400:        b99eea2a         ldrsw        x10, [x17, #7912]
+ 404:        fd5a2f8d         ldr        d13, [x28, #13400]
+ 408:        bd5dac78         ldr        s24, [x3, #7596]
+ 40c:        fd1e0182         str        d2, [x12, #15360]
+ 410:        bd195c31         str        s17, [x1, #6492]
+ 414:        58000010         ldr        x16, 414 <back+0x414>
+ 418:        1800000d         ldr        w13, 418 <back+0x418>
+ 41c:        f8981240         prfum        pldl1keep, [x18, #-127]
+ 420:        d8ffdf00         prfm        pldl1keep, 0 <back>
+ 424:        f8a27a80         prfm        pldl1keep, [x20, x2, lsl #3]
+ 428:        f99af920         prfm        pldl1keep, [x9, #13808]
+ 42c:        1a0202e8         adc        w8, w23, w2
+ 430:        3a130078         adcs        w24, w3, w19
+ 434:        5a1d0316         sbc        w22, w24, w29
+ 438:        7a03036c         sbcs        w12, w27, w3
+ 43c:        9a0102eb         adc        x11, x23, x1
+ 440:        ba1700bd         adcs        x29, x5, x23
+ 444:        da0c0329         sbc        x9, x25, x12
+ 448:        fa16000c         sbcs        x12, x0, x22
+ 44c:        0b23459a         add        w26, w12, w3, uxtw #1
+ 450:        2b328a14         adds        w20, w16, w18, sxtb #2
+ 454:        cb274bde         sub        x30, x30, w7, uxtw #2
+ 458:        6b222eab         subs        w11, w21, w2, uxth #3
+ 45c:        8b214b42         add        x2, x26, w1, uxtw #2
+ 460:        ab34a7b2         adds        x18, x29, w20, sxth #1
+ 464:        cb24520e         sub        x14, x16, w4, uxtw #4
+ 468:        eb378e20         subs        x0, x17, w23, sxtb #3
+ 46c:        3a565283         ccmn        w20, w22, #0x3, pl  // pl = nfrst
+ 470:        7a420321         ccmp        w25, w2, #0x1, eq  // eq = none
+ 474:        ba58c247         ccmn        x18, x24, #0x7, gt
+ 478:        fa4d5106         ccmp        x8, x13, #0x6, pl  // pl = nfrst
+ 47c:        3a426924         ccmn        w9, #0x2, #0x4, vs
+ 480:        7a5b0847         ccmp        w2, #0x1b, #0x7, eq  // eq = none
+ 484:        ba413a02         ccmn        x16, #0x1, #0x2, cc  // cc = lo, ul, last
+ 488:        fa5fba23         ccmp        x17, #0x1f, #0x3, lt  // lt = tstop
+ 48c:        1a979377         csel        w23, w27, w23, ls  // ls = plast
+ 490:        1a86640a         csinc        w10, w0, w6, vs
+ 494:        5a89300b         csinv        w11, w0, w9, cc  // cc = lo, ul, last
+ 498:        5a923771         csneg        w17, w27, w18, cc  // cc = lo, ul, last
+ 49c:        9a8b720c         csel        x12, x16, x11, vc
+ 4a0:        9a868786         csinc        x6, x28, x6, hi  // hi = pmore
+ 4a4:        da9a736d         csinv        x13, x27, x26, vc
+ 4a8:        da9256dd         csneg        x29, x22, x18, pl  // pl = nfrst
+ 4ac:        5ac0026c         rbit        w12, w19
+ 4b0:        5ac00657         rev16        w23, w18
+ 4b4:        5ac00b89         rev        w9, w28
+ 4b8:        5ac01262         clz        w2, w19
+ 4bc:        5ac017b9         cls        w25, w29
+ 4c0:        dac002e4         rbit        x4, x23
+ 4c4:        dac0065d         rev16        x29, x18
+ 4c8:        dac00907         rev32        x7, x8
+ 4cc:        dac00e2d         rev        x13, x17
+ 4d0:        dac01011         clz        x17, x0
+ 4d4:        dac01752         cls        x18, x26
+ 4d8:        1ad0098b         udiv        w11, w12, w16
+ 4dc:        1ac70d24         sdiv        w4, w9, w7
+ 4e0:        1ad020ec         lsl        w12, w7, w16
+ 4e4:        1ad72613         lsr        w19, w16, w23
+ 4e8:        1ac62887         asr        w7, w4, w6
+ 4ec:        1ad72e95         ror        w21, w20, w23
+ 4f0:        9adc0990         udiv        x16, x12, x28
+ 4f4:        9acd0d84         sdiv        x4, x12, x13
+ 4f8:        9ac721a9         lsl        x9, x13, x7
+ 4fc:        9acf277c         lsr        x28, x27, x15
+ 500:        9ace2bd4         asr        x20, x30, x14
+ 504:        9ade2e4e         ror        x14, x18, x30
+ 508:        9bc77d63         umulh        x3, x11, x7
+ 50c:        9b587e97         smulh        x23, x20, x24
+ 510:        1b1524a2         madd        w2, w5, w21, w9
+ 514:        1b04a318         msub        w24, w24, w4, w8
+ 518:        9b0f4d8b         madd        x11, x12, x15, x19
+ 51c:        9b0ce73d         msub        x29, x25, x12, x25
+ 520:        9b2c5971         smaddl        x17, w11, w12, x22
+ 524:        9b34c87c         smsubl        x28, w3, w20, x18
+ 528:        9bbc6887         umaddl        x7, w4, w28, x26
+ 52c:        9bb19556         umsubl        x22, w10, w17, x5
+ 530:        1e310871         fmul        s17, s3, s17
+ 534:        1e261a2b         fdiv        s11, s17, s6
+ 538:        1e2928fd         fadd        s29, s7, s9
+ 53c:        1e333987         fsub        s7, s12, s19
+ 540:        1e230ae0         fmul        s0, s23, s3
+ 544:        1e75087a         fmul        d26, d3, d21
+ 548:        1e651a60         fdiv        d0, d19, d5
+ 54c:        1e692b40         fadd        d0, d26, d9
+ 550:        1e753ab9         fsub        d25, d21, d21
+ 554:        1e7309b0         fmul        d16, d13, d19
+ 558:        1f00425d         fmadd        s29, s18, s0, s16
+ 55c:        1f1d95b7         fmsub        s23, s13, s29, s5
+ 560:        1f2a38e9         fnmadd        s9, s7, s10, s14
+ 564:        1f2f5f99         fnmadd        s25, s28, s15, s23
+ 568:        1f5545a6         fmadd        d6, d13, d21, d17
+ 56c:        1f429ea3         fmsub        d3, d21, d2, d7
+ 570:        1f65472a         fnmadd        d10, d25, d5, d17
+ 574:        1f7449ce         fnmadd        d14, d14, d20, d18
+ 578:        1e20404f         fmov        s15, s2
+ 57c:        1e20c0f2         fabs        s18, s7
+ 580:        1e2140c3         fneg        s3, s6
+ 584:        1e21c02c         fsqrt        s12, s1
+ 588:        1e22c009         fcvt        d9, s0
+ 58c:        1e6040a4         fmov        d4, d5
+ 590:        1e60c1e3         fabs        d3, d15
+ 594:        1e614331         fneg        d17, d25
+ 598:        1e61c30c         fsqrt        d12, d24
+ 59c:        1e6240b5         fcvt        s21, d5
+ 5a0:        1e3802a4         fcvtzs        w4, s21
+ 5a4:        9e38007b         fcvtzs        x27, s3
+ 5a8:        1e78011d         fcvtzs        w29, d8
+ 5ac:        9e7802a9         fcvtzs        x9, d21
+ 5b0:        1e2203b4         scvtf        s20, w29
+ 5b4:        9e220107         scvtf        s7, x8
+ 5b8:        1e6202ac         scvtf        d12, w21
+ 5bc:        9e6202b0         scvtf        d16, x21
+ 5c0:        1e2600b2         fmov        w18, s5
+ 5c4:        9e660119         fmov        x25, d8
+ 5c8:        1e270352         fmov        s18, w26
+ 5cc:        9e670160         fmov        d0, x11
+ 5d0:        1e262200         fcmp        s16, s6
+ 5d4:        1e7d2200         fcmp        d16, d29
+ 5d8:        1e2023c8         fcmp        s30, #0.0
+ 5dc:        1e602128         fcmp        d9, #0.0
+ 5e0:        293e119b         stp        w27, w4, [x12, #-16]
+ 5e4:        294a2543         ldp        w3, w9, [x10, #80]
+ 5e8:        69480c70         ldpsw        x16, x3, [x3, #64]
+ 5ec:        a934726a         stp        x10, x28, [x19, #-192]
+ 5f0:        a97448f3         ldp        x19, x18, [x7, #-192]
+ 5f4:        298243ca         stp        w10, w16, [x30, #16]!
+ 5f8:        29e21242         ldp        w2, w4, [x18, #-240]!
+ 5fc:        69c64db8         ldpsw        x24, x19, [x13, #48]!
+ 600:        a9800311         stp        x17, x0, [x24, #0]!
+ 604:        a9f4686e         ldp        x14, x26, [x3, #-192]!
+ 608:        288a0416         stp        w22, w1, [x0], #80
+ 60c:        28fe2812         ldp        w18, w10, [x0], #-16
+ 610:        68fe62d8         .inst        0x68fe62d8 ; undefined
+ 614:        a885308c         stp        x12, x12, [x4], #80
+ 618:        a8f12664         ldp        x4, x9, [x19], #-240
+ 61c:        282468d2         stnp        w18, w26, [x6, #-224]
+ 620:        284e5035         ldnp        w21, w20, [x1, #112]
+ 624:        a8327699         stnp        x25, x29, [x20, #-224]
+ 628:        a84716e1         ldnp        x1, x5, [x23, #112]
+ 62c:        0c407284         ld1        {v4.8b}, [x20]
+ 630:        4cdfa158         ld1        {v24.16b, v25.16b}, [x10], #32
+ 634:        0ccf6cd8         ld1        {v24.1d-v26.1d}, [x6], x15
+ 638:        4cdf2483         ld1        {v3.8h-v6.8h}, [x4], #64
+ 63c:        0d40c0c2         ld1r        {v2.8b}, [x6]
+ 640:        4ddfc9cd         ld1r        {v13.4s}, [x14], #4
+ 644:        0dd8ceaf         ld1r        {v15.1d}, [x21], x24
+ 648:        4c408ea9         ld2        {v9.2d, v10.2d}, [x21]
+ 64c:        0cdf86bd         ld2        {v29.4h, v30.4h}, [x21], #16
+ 650:        4d60c1c8         ld2r        {v8.16b, v9.16b}, [x14]
+ 654:        0dffca87         ld2r        {v7.2s, v8.2s}, [x20], #8
+ 658:        4de3cc7c         ld2r        {v28.2d, v29.2d}, [x3], x3
+ 65c:        4cdd497b         ld3        {v27.4s-v29.4s}, [x11], x29
+ 660:        0c404950         ld3        {v16.2s-v18.2s}, [x10]
+ 664:        4d40e595         ld3r        {v21.8h-v23.8h}, [x12]
+ 668:        4ddfeba4         ld3r        {v4.4s-v6.4s}, [x29], #12
+ 66c:        0dd3ed38         ld3r        {v24.1d-v26.1d}, [x9], x19
+ 670:        4cdf046a         ld4        {v10.8h-v13.8h}, [x3], #64
+ 674:        0cc9039b         ld4        {v27.8b-v30.8b}, [x28], x9
+ 678:        0d60e3d5         ld4r        {v21.8b-v24.8b}, [x30]
+ 67c:        0dffe5d7         ld4r        {v23.4h-v26.4h}, [x14], #8
+ 680:        0df4e9a4         ld4r        {v4.2s-v7.2s}, [x13], x20
+ 684:        ba5fd3e3         ccmn        xzr, xzr, #0x3, le
+ 688:        3a5f03e5         ccmn        wzr, wzr, #0x5, eq  // eq = none
+ 68c:        fa411be4         ccmp        xzr, #0x1, #0x4, ne  // ne = any
+ 690:        7a42cbe2         ccmp        wzr, #0x2, #0x2, gt
+ 694:        93df03ff         ror        xzr, xzr, #0
+ 698:        c820ffff         stlxp        w0, xzr, xzr, [sp]
+ 69c:        8822fc7f         stlxp        w2, wzr, wzr, [x3]
+ 6a0:        c8247cbf         stxp        w4, xzr, xzr, [x5]
+ 6a4:        88267fff         stxp        w6, wzr, wzr, [sp]
+ 6a8:        4e010fe0         dup        v0.16b, wzr
+ 6ac:        4e081fe1         mov        v1.d[0], xzr
+ 6b0:        4e0c1fe1         mov        v1.s[1], wzr
+ 6b4:        4e0a1fe1         mov        v1.h[2], wzr
+ 6b8:        4e071fe1         mov        v1.b[3], wzr
+ 6bc:        4cc0ac3f         ld1        {v31.2d, v0.2d}, [x1], x0
+ 6c0:        1e601000         fmov        d0, #2.000000000000000000e+00
+ 6c4:        1e603000         fmov        d0, #2.125000000000000000e+00
+ 6c8:        1e621000         fmov        d0, #4.000000000000000000e+00
+ 6cc:        1e623000         fmov        d0, #4.250000000000000000e+00
+ 6d0:        1e641000         fmov        d0, #8.000000000000000000e+00
+ 6d4:        1e643000         fmov        d0, #8.500000000000000000e+00
+ 6d8:        1e661000         fmov        d0, #1.600000000000000000e+01
+ 6dc:        1e663000         fmov        d0, #1.700000000000000000e+01
+ 6e0:        1e681000         fmov        d0, #1.250000000000000000e-01
+ 6e4:        1e683000         fmov        d0, #1.328125000000000000e-01
+ 6e8:        1e6a1000         fmov        d0, #2.500000000000000000e-01
+ 6ec:        1e6a3000         fmov        d0, #2.656250000000000000e-01
+ 6f0:        1e6c1000         fmov        d0, #5.000000000000000000e-01
+ 6f4:        1e6c3000         fmov        d0, #5.312500000000000000e-01
+ 6f8:        1e6e1000         fmov        d0, #1.000000000000000000e+00
+ 6fc:        1e6e3000         fmov        d0, #1.062500000000000000e+00
+ 700:        1e701000         fmov        d0, #-2.000000000000000000e+00
+ 704:        1e703000         fmov        d0, #-2.125000000000000000e+00
+ 708:        1e721000         fmov        d0, #-4.000000000000000000e+00
+ 70c:        1e723000         fmov        d0, #-4.250000000000000000e+00
+ 710:        1e741000         fmov        d0, #-8.000000000000000000e+00
+ 714:        1e743000         fmov        d0, #-8.500000000000000000e+00
+ 718:        1e761000         fmov        d0, #-1.600000000000000000e+01
+ 71c:        1e763000         fmov        d0, #-1.700000000000000000e+01
+ 720:        1e781000         fmov        d0, #-1.250000000000000000e-01
+ 724:        1e783000         fmov        d0, #-1.328125000000000000e-01
+ 728:        1e7a1000         fmov        d0, #-2.500000000000000000e-01
+ 72c:        1e7a3000         fmov        d0, #-2.656250000000000000e-01
+ 730:        1e7c1000         fmov        d0, #-5.000000000000000000e-01
+ 734:        1e7c3000         fmov        d0, #-5.312500000000000000e-01
+ 738:        1e7e1000         fmov        d0, #-1.000000000000000000e+00
+ 73c:        1e7e3000         fmov        d0, #-1.062500000000000000e+00
+ 740:        f8358305         swp        x21, x5, [x24]
+ 744:        f82d01ed         ldadd        x13, x13, [x15]
+ 748:        f8361353         ldclr        x22, x19, [x26]
+ 74c:        f839234a         ldeor        x25, x10, [x26]
+ 750:        f82531fb         ldset        x5, x27, [x15]
+ 754:        f8335165         ldsmin        x19, x5, [x11]
+ 758:        f83a4080         ldsmax        x26, x0, [x4]
+ 75c:        f83673d7         ldumin        x22, x23, [x30]
+ 760:        f832611c         ldumax        x18, x28, [x8]
+ 764:        f8ad837d         swpa        x13, x29, [x27]
+ 768:        f8ab01a5         ldadda        x11, x5, [x13]
+ 76c:        f8a112b8         ldclra        x1, x24, [x21]
+ 770:        f8bb2311         ldeora        x27, x17, [x24]
+ 774:        f8b230be         ldseta        x18, x30, [x5]
+ 778:        f8a75336         ldsmina        x7, x22, [x25]
+ 77c:        f8a4427a         ldsmaxa        x4, x26, [x19]
+ 780:        f8a6707e         ldumina        x6, x30, [x3]
+ 784:        f8b860b7         ldumaxa        x24, x23, [x5]
+ 788:        f8f88392         swpal        x24, x18, [x28]
+ 78c:        f8f300ff         ldaddal        x19, xzr, [x7]
+ 790:        f8ed1386         ldclral        x13, x6, [x28]
+ 794:        f8e822af         ldeoral        x8, x15, [x21]
+ 798:        f8e2302d         ldsetal        x2, x13, [x1]
+ 79c:        f8f1533d         ldsminal        x17, x29, [x25]
+ 7a0:        f8f941d2         ldsmaxal        x25, x18, [x14]
+ 7a4:        f8ff7366         lduminal        xzr, x6, [x27]
+ 7a8:        f8f061e5         ldumaxal        x16, x5, [x15]
+ 7ac:        f86b8072         swpl        x11, x18, [x3]
+ 7b0:        f87a0054         ldaddl        x26, x20, [x2]
+ 7b4:        f86b1164         ldclrl        x11, x4, [x11]
+ 7b8:        f87e22f3         ldeorl        x30, x19, [x23]
+ 7bc:        f86331cf         ldsetl        x3, x15, [x14]
+ 7c0:        f87e5296         ldsminl        x30, x22, [x20]
+ 7c4:        f8674305         ldsmaxl        x7, x5, [x24]
+ 7c8:        f87771f0         lduminl        x23, x16, [x15]
+ 7cc:        f86b6013         ldumaxl        x11, x19, [x0]
+ 7d0:        b83c803c         swp        w28, w28, [x1]
+ 7d4:        b82b0195         ldadd        w11, w21, [x12]
+ 7d8:        b83d1240         ldclr        w29, w0, [x18]
+ 7dc:        b8252320         ldeor        w5, w0, [x25]
+ 7e0:        b82e3340         ldset        w14, w0, [x26]
+ 7e4:        b83c53b2         ldsmin        w28, w18, [x29]
+ 7e8:        b82f43a1         ldsmax        w15, w1, [x29]
+ 7ec:        b828739a         ldumin        w8, w26, [x28]
+ 7f0:        b831608e         ldumax        w17, w14, [x4]
+ 7f4:        b8b88039         swpa        w24, w25, [x1]
+ 7f8:        b8aa0231         ldadda        w10, w17, [x17]
+ 7fc:        b8bd12b4         ldclra        w29, w20, [x21]
+ 800:        b8bd2189         ldeora        w29, w9, [x12]
+ 804:        b8ab30a6         ldseta        w11, w6, [x5]
+ 808:        b8b552a7         ldsmina        w21, w7, [x21]
+ 80c:        b8aa4197         ldsmaxa        w10, w23, [x12]
+ 810:        b8b57145         ldumina        w21, w5, [x10]
+ 814:        b8be6254         ldumaxa        w30, w20, [x18]
+ 818:        b8ed80b7         swpal        w13, w23, [x5]
+ 81c:        b8ef00b8         ldaddal        w15, w24, [x5]
+ 820:        b8e9132a         ldclral        w9, w10, [x25]
+ 824:        b8f42231         ldeoral        w20, w17, [x17]
+ 828:        b8ec33d2         ldsetal        w12, w18, [x30]
+ 82c:        b8e35323         ldsminal        w3, w3, [x25]
+ 830:        b8fa4159         ldsmaxal        w26, w25, [x10]
+ 834:        b8e273eb         lduminal        w2, w11, [sp]
+ 838:        b8e760a2         ldumaxal        w7, w2, [x5]
+ 83c:        b8608287         swpl        w0, w7, [x20]
+ 840:        b865005f         staddl        w5, [x2]
+ 844:        b87b1379         ldclrl        w27, w25, [x27]
+ 848:        b87e2358         ldeorl        w30, w24, [x26]
+ 84c:        b86f32c2         ldsetl        w15, w2, [x22]
+ 850:        b86053e3         ldsminl        w0, w3, [sp]
+ 854:        b86f4154         ldsmaxl        w15, w20, [x10]
+ 858:        b87671d5         lduminl        w22, w21, [x14]
+ 85c:        b866605e         ldumaxl        w6, w30, [x2]
  */
 
   static const unsigned int insns[] =
   {
-    0x8b0772d3,     0xcb4a3570,     0xab9c09bb,     0xeb9aa794,
-    0x0b934e68,     0x4b0a3924,     0x2b1e3568,     0x6b132720,
-    0x8a154c14,     0xaa1445d5,     0xca01cf99,     0xea8b3f6a,
-    0x0a8c5cb9,     0x2a4a11d2,     0x4a855aa4,     0x6a857415,
-    0x8aa697da,     0xaa6d7423,     0xca29bf80,     0xea3cb8bd,
-    0x0a675249,     0x2ab961ba,     0x4a331899,     0x6a646345,
-    0x11055267,     0x31064408,     0x51028e9d,     0x710bdee8,
-    0x91082d81,     0xb106a962,     0xd10b33ae,     0xf10918ab,
-    0x121102d7,     0x3204cd44,     0x5204cf00,     0x72099fb3,
-    0x92729545,     0xb20e37cc,     0xd27c34be,     0xf27e4efa,
-    0x14000000,     0x17ffffd7,     0x1400017f,     0x94000000,
-    0x97ffffd4,     0x9400017c,     0x3400000c,     0x34fffa2c,
-    0x34002f2c,     0x35000014,     0x35fff9d4,     0x35002ed4,
-    0xb400000c,     0xb4fff96c,     0xb4002e6c,     0xb5000018,
-    0xb5fff918,     0xb5002e18,     0x10000006,     0x10fff8a6,
-    0x10002da6,     0x90000015,     0x36080001,     0x360ff821,
-    0x36082d21,     0x37480008,     0x374ff7c8,     0x37482cc8,
-    0x128b50ec,     0x52a9ff8b,     0x7281d095,     0x92edfebd,
-    0xd28361e3,     0xf2a4cc96,     0x9346590c,     0x33194f33,
-    0x531d3d89,     0x9350433c,     0xb34464ac,     0xd3462140,
-    0x139a61a4,     0x93d87fd7,     0x54000000,     0x54fff5a0,
-    0x54002aa0,     0x54000001,     0x54fff541,     0x54002a41,
-    0x54000002,     0x54fff4e2,     0x540029e2,     0x54000002,
-    0x54fff482,     0x54002982,     0x54000003,     0x54fff423,
-    0x54002923,     0x54000003,     0x54fff3c3,     0x540028c3,
-    0x54000004,     0x54fff364,     0x54002864,     0x54000005,
-    0x54fff305,     0x54002805,     0x54000006,     0x54fff2a6,
-    0x540027a6,     0x54000007,     0x54fff247,     0x54002747,
-    0x54000008,     0x54fff1e8,     0x540026e8,     0x54000009,
-    0x54fff189,     0x54002689,     0x5400000a,     0x54fff12a,
-    0x5400262a,     0x5400000b,     0x54fff0cb,     0x540025cb,
-    0x5400000c,     0x54fff06c,     0x5400256c,     0x5400000d,
-    0x54fff00d,     0x5400250d,     0x5400000e,     0x54ffefae,
-    0x540024ae,     0x5400000f,     0x54ffef4f,     0x5400244f,
-    0xd4063721,     0xd4035082,     0xd400bfe3,     0xd4282fc0,
-    0xd444c320,     0xd503201f,     0xd69f03e0,     0xd6bf03e0,
-    0xd5033fdf,     0xd5033f9f,     0xd5033abf,     0xd61f0040,
-    0xd63f00a0,     0xc8147c55,     0xc805fcfd,     0xc85f7e05,
-    0xc85fffbb,     0xc89fffa0,     0xc8dfff95,     0x88157cf8,
-    0x8815ff9a,     0x885f7cd5,     0x885fffcf,     0x889ffc73,
-    0x88dffc56,     0x48127c0f,     0x480bff85,     0x485f7cdd,
-    0x485ffcf2,     0x489fff99,     0x48dffe62,     0x080a7c3e,
-    0x0814fed5,     0x085f7c59,     0x085ffcb8,     0x089ffc70,
-    0x08dfffb6,     0xc87f0a68,     0xc87fcdc7,     0xc82870bb,
-    0xc825b8c8,     0x887f12d9,     0x887fb9ed,     0x8834215a,
-    0x8837ca52,     0xf806317e,     0xb81b3337,     0x39000dc2,
-    0x78005149,     0xf84391f4,     0xb85b220c,     0x385fd356,
-    0x785d127e,     0x389f4149,     0x79801e3c,     0x79c014a3,
-    0xb89a5231,     0xfc5ef282,     0xbc5f60f6,     0xfc12125e,
-    0xbc0152cd,     0xf8190e49,     0xb800befd,     0x381ffd92,
-    0x781e9e90,     0xf8409fa3,     0xb8413c79,     0x385fffa1,
-    0x785c7fa8,     0x389f3dc5,     0x78801f6a,     0x78c19d4b,
-    0xb89a4ec4,     0xfc408eeb,     0xbc436e79,     0xfc152ce1,
-    0xbc036f28,     0xf8025565,     0xb80135f8,     0x381ff74f,
-    0x781fa652,     0xf851a447,     0xb85e557b,     0x385e7472,
-    0x785e070a,     0x38804556,     0x78819591,     0x78dc24e8,
-    0xb89cd6d7,     0xfc430738,     0xbc5f6595,     0xfc1225b2,
-    0xbc1d7430,     0xf82fcac2,     0xb83d6a02,     0x382e5a54,
-    0x7834fa66,     0xf86ecbae,     0xb86cda90,     0x3860d989,
-    0x78637a2c,     0x38a3fa22,     0x78b15827,     0x78f2d9f9,
-    0xb8ac6ab7,     0xfc6879a5,     0xbc767943,     0xfc3bc84e,
-    0xbc3968d4,     0xf91fc0fe,     0xb91da50f,     0x391d280b,
-    0x791d2e23,     0xf95bc8e2,     0xb95ce525,     0x395ae53c,
-    0x795c9282,     0x399d7dd6,     0x799fe008,     0x79de9bc0,
-    0xb99aae78,     0xfd597598,     0xbd5d1d08,     0xfd1f3dea,
-    0xbd1a227a,     0x5800148a,     0x18000003,     0xf88092e0,
-    0xd8ffdf00,     0xf8a84860,     0xf99d7560,     0x1a1c012d,
-    0x3a1c027b,     0x5a060253,     0x7a03028e,     0x9a0801d0,
-    0xba0803a0,     0xda140308,     0xfa00038c,     0x0b3010d7,
-    0x2b37ab39,     0xcb2466da,     0x6b33efb1,     0x8b350fcb,
-    0xab208a70,     0xcb39e52b,     0xeb2c9291,     0x3a4bd1a3,
-    0x7a4c81a2,     0xba42106c,     0xfa5560e3,     0x3a4e3844,
-    0x7a515a26,     0xba4c2940,     0xfa52aaae,     0x1a8cc1b5,
-    0x1a8f976a,     0x5a8981a0,     0x5a9a6492,     0x9a8793ac,
-    0x9a9474e6,     0xda83d2b6,     0xda9b9593,     0x5ac00200,
-    0x5ac006f1,     0x5ac009d1,     0x5ac013d8,     0x5ac016d8,
-    0xdac00223,     0xdac005ac,     0xdac00ac9,     0xdac00c00,
-    0xdac01205,     0xdac016d9,     0x1ac0089d,     0x1add0fa0,
-    0x1ad52225,     0x1ad22529,     0x1ac82b61,     0x1acd2e92,
-    0x9acc0b28,     0x9adc0ca7,     0x9adb2225,     0x9ad42757,
-    0x9adc291c,     0x9ac42fa3,     0x1b1a55d1,     0x1b0bafc1,
-    0x9b067221,     0x9b1ea0de,     0x9b2e20d5,     0x9b38cd4a,
-    0x9bae6254,     0x9ba59452,     0x1e2d0a48,     0x1e3c19c2,
-    0x1e3c298f,     0x1e213980,     0x1e240baf,     0x1e77082c,
-    0x1e72191b,     0x1e6b2a97,     0x1e723988,     0x1e770b1a,
-    0x1f0d66f5,     0x1f01b956,     0x1f227a8e,     0x1f365ba7,
-    0x1f4f14ad,     0x1f45a98e,     0x1f60066a,     0x1f620054,
-    0x1e204139,     0x1e20c094,     0x1e214363,     0x1e21c041,
-    0x1e22c01e,     0x1e60408c,     0x1e60c361,     0x1e6142c8,
-    0x1e61c16b,     0x1e624396,     0x1e3802dc,     0x9e380374,
-    0x1e78000e,     0x9e78017a,     0x1e2202dc,     0x9e220150,
-    0x1e6202a8,     0x9e620395,     0x1e260318,     0x9e660268,
-    0x1e270188,     0x9e6700e6,     0x1e3023c0,     0x1e6b2320,
-    0x1e202168,     0x1e602168,     0x2910323d,     0x297449d6,
-    0x6948402b,     0xa9072f40,     0xa9410747,     0x29801f0a,
-    0x29e07307,     0x69e272b9,     0xa9bf49d4,     0xa9c529a8,
-    0x28b0605a,     0x28e866a2,     0x68ee0ab1,     0xa886296c,
-    0xa8fe1a38,     0x282479c3,     0x286e534f,     0xa8386596,
-    0xa8755a3b,     0x1e601000,     0x1e603000,     0x1e621000,
-    0x1e623000,     0x1e641000,     0x1e643000,     0x1e661000,
-    0x1e663000,     0x1e681000,     0x1e683000,     0x1e6a1000,
-    0x1e6a3000,     0x1e6c1000,     0x1e6c3000,     0x1e6e1000,
-    0x1e6e3000,     0x1e701000,     0x1e703000,     0x1e721000,
-    0x1e723000,     0x1e741000,     0x1e743000,     0x1e761000,
-    0x1e763000,     0x1e781000,     0x1e783000,     0x1e7a1000,
-    0x1e7a3000,     0x1e7c1000,     0x1e7c3000,     0x1e7e1000,
-    0x1e7e3000,
+    0x8b50798f,     0xcb4381e1,     0xab05372d,     0xeb864796,
+    0x0b961920,     0x4b195473,     0x2b0b5264,     0x6b9300f8,
+    0x8a0bc0fe,     0xaa0f3118,     0xca170531,     0xea44dd6e,
+    0x0a4c44f3,     0x2a8b7373,     0x4a567c7e,     0x6a9c0353,
+    0x8a3accdd,     0xaa318f7a,     0xca2e1495,     0xeaa015e2,
+    0x0a2274e2,     0x2a751598,     0x4a3309fe,     0x6ab172fe,
+    0x110a5284,     0x310b1942,     0x5103d353,     0x710125bc,
+    0x910d7bc2,     0xb108fa1b,     0xd1093536,     0xf10ae824,
+    0x120e667c,     0x321f6cbb,     0x520f6a9e,     0x72136f56,
+    0x927e4ce5,     0xb278b4ed,     0xd24c6527,     0xf2485803,
+    0x14000000,     0x17ffffd7,     0x140001ee,     0x94000000,
+    0x97ffffd4,     0x940001eb,     0x34000010,     0x34fffa30,
+    0x34003d10,     0x35000013,     0x35fff9d3,     0x35003cb3,
+    0xb4000005,     0xb4fff965,     0xb4003c45,     0xb5000004,
+    0xb5fff904,     0xb5003be4,     0x1000001b,     0x10fff8bb,
+    0x10003b9b,     0x90000010,     0x3640001c,     0x3647f83c,
+    0x36403b1c,     0x37080001,     0x370ff7c1,     0x37083aa1,
+    0x12a437f4,     0x528c9d67,     0x72838bb1,     0x92c1062e,
+    0xd287da49,     0xf2a6d153,     0x93465ac9,     0x330b0013,
+    0x530b4e6a,     0x934545e4,     0xb35370a3,     0xd3510b8c,
+    0x13960c0f,     0x93ceddc6,     0x54000000,     0x54fff5a0,
+    0x54003880,     0x54000001,     0x54fff541,     0x54003821,
+    0x54000002,     0x54fff4e2,     0x540037c2,     0x54000002,
+    0x54fff482,     0x54003762,     0x54000003,     0x54fff423,
+    0x54003703,     0x54000003,     0x54fff3c3,     0x540036a3,
+    0x54000004,     0x54fff364,     0x54003644,     0x54000005,
+    0x54fff305,     0x540035e5,     0x54000006,     0x54fff2a6,
+    0x54003586,     0x54000007,     0x54fff247,     0x54003527,
+    0x54000008,     0x54fff1e8,     0x540034c8,     0x54000009,
+    0x54fff189,     0x54003469,     0x5400000a,     0x54fff12a,
+    0x5400340a,     0x5400000b,     0x54fff0cb,     0x540033ab,
+    0x5400000c,     0x54fff06c,     0x5400334c,     0x5400000d,
+    0x54fff00d,     0x540032ed,     0x5400000e,     0x54ffefae,
+    0x5400328e,     0x5400000f,     0x54ffef4f,     0x5400322f,
+    0xd40ac601,     0xd40042a2,     0xd404dac3,     0xd4224d40,
+    0xd44219c0,     0xd503201f,     0xd69f03e0,     0xd6bf03e0,
+    0xd5033fdf,     0xd503339f,     0xd50335bf,     0xd61f0280,
+    0xd63f0040,     0xc8127c17,     0xc81efec5,     0xc85f7d05,
+    0xc85ffe14,     0xc89ffd66,     0xc8dfff66,     0x880a7cb1,
+    0x8816fd89,     0x885f7d1b,     0x885ffc57,     0x889fffba,
+    0x88dffd4d,     0x48197f7c,     0x481dfd96,     0x485f7f96,
+    0x485fffc3,     0x489ffdf8,     0x48dfff5b,     0x080b7e6a,
+    0x0817fedb,     0x085f7e18,     0x085ffc38,     0x089fffa5,
+    0x08dffe18,     0xc87f6239,     0xc87fb276,     0xc820573a,
+    0xc821aca6,     0x887f388d,     0x887f88d1,     0x882f2643,
+    0x88329131,     0xf81cf2b7,     0xb803f055,     0x39002f9b,
+    0x781f31fd,     0xf85d33ce,     0xb843539d,     0x39401f54,
+    0x785ce059,     0x389f1143,     0x788131ee,     0x78dfb17d,
+    0xb89b90af,     0xfc403193,     0xbc42a36c,     0xfc07d396,
+    0xbc1ec1f8,     0xf81e8f88,     0xb8025de6,     0x38007c27,
+    0x7801ee20,     0xf8454fb9,     0xb85cce9a,     0x385e7fba,
+    0x7841af24,     0x389ebd1c,     0x789fadd1,     0x78c0aefc,
+    0xb89c0f7e,     0xfc50efd4,     0xbc414f71,     0xfc011c67,
+    0xbc1f0d6d,     0xf81c3526,     0xb81e34b0,     0x3800f7bd,
+    0x78012684,     0xf842e653,     0xb8417456,     0x385e2467,
+    0x785e358b,     0x389e34c8,     0x788046f8,     0x78c00611,
+    0xb89f8680,     0xfc582454,     0xbc5987d3,     0xfc076624,
+    0xbc190675,     0xf833785a,     0xb82fd809,     0x3821799a,
+    0x782a7975,     0xf870eaf0,     0xb871d96a,     0x386b7aed,
+    0x7875689b,     0x38afd91a,     0x78a2c955,     0x78ee6bc8,
+    0xb8b4f9dd,     0xfc76eb7e,     0xbc76692d,     0xfc31db28,
+    0xbc255b01,     0xf91c52aa,     0xb91c3fb2,     0x391f8877,
+    0x791ac97c,     0xf95c1758,     0xb95b3c55,     0x395ce0a4,
+    0x795851ce,     0x399e9f64,     0x79993764,     0x79d9af8a,
+    0xb99eea2a,     0xfd5a2f8d,     0xbd5dac78,     0xfd1e0182,
+    0xbd195c31,     0x58000010,     0x1800000d,     0xf8981240,
+    0xd8ffdf00,     0xf8a27a80,     0xf99af920,     0x1a0202e8,
+    0x3a130078,     0x5a1d0316,     0x7a03036c,     0x9a0102eb,
+    0xba1700bd,     0xda0c0329,     0xfa16000c,     0x0b23459a,
+    0x2b328a14,     0xcb274bde,     0x6b222eab,     0x8b214b42,
+    0xab34a7b2,     0xcb24520e,     0xeb378e20,     0x3a565283,
+    0x7a420321,     0xba58c247,     0xfa4d5106,     0x3a426924,
+    0x7a5b0847,     0xba413a02,     0xfa5fba23,     0x1a979377,
+    0x1a86640a,     0x5a89300b,     0x5a923771,     0x9a8b720c,
+    0x9a868786,     0xda9a736d,     0xda9256dd,     0x5ac0026c,
+    0x5ac00657,     0x5ac00b89,     0x5ac01262,     0x5ac017b9,
+    0xdac002e4,     0xdac0065d,     0xdac00907,     0xdac00e2d,
+    0xdac01011,     0xdac01752,     0x1ad0098b,     0x1ac70d24,
+    0x1ad020ec,     0x1ad72613,     0x1ac62887,     0x1ad72e95,
+    0x9adc0990,     0x9acd0d84,     0x9ac721a9,     0x9acf277c,
+    0x9ace2bd4,     0x9ade2e4e,     0x9bc77d63,     0x9b587e97,
+    0x1b1524a2,     0x1b04a318,     0x9b0f4d8b,     0x9b0ce73d,
+    0x9b2c5971,     0x9b34c87c,     0x9bbc6887,     0x9bb19556,
+    0x1e310871,     0x1e261a2b,     0x1e2928fd,     0x1e333987,
+    0x1e230ae0,     0x1e75087a,     0x1e651a60,     0x1e692b40,
+    0x1e753ab9,     0x1e7309b0,     0x1f00425d,     0x1f1d95b7,
+    0x1f2a38e9,     0x1f2f5f99,     0x1f5545a6,     0x1f429ea3,
+    0x1f65472a,     0x1f7449ce,     0x1e20404f,     0x1e20c0f2,
+    0x1e2140c3,     0x1e21c02c,     0x1e22c009,     0x1e6040a4,
+    0x1e60c1e3,     0x1e614331,     0x1e61c30c,     0x1e6240b5,
+    0x1e3802a4,     0x9e38007b,     0x1e78011d,     0x9e7802a9,
+    0x1e2203b4,     0x9e220107,     0x1e6202ac,     0x9e6202b0,
+    0x1e2600b2,     0x9e660119,     0x1e270352,     0x9e670160,
+    0x1e262200,     0x1e7d2200,     0x1e2023c8,     0x1e602128,
+    0x293e119b,     0x294a2543,     0x69480c70,     0xa934726a,
+    0xa97448f3,     0x298243ca,     0x29e21242,     0x69c64db8,
+    0xa9800311,     0xa9f4686e,     0x288a0416,     0x28fe2812,
+    0x68fe62d8,     0xa885308c,     0xa8f12664,     0x282468d2,
+    0x284e5035,     0xa8327699,     0xa84716e1,     0x0c407284,
+    0x4cdfa158,     0x0ccf6cd8,     0x4cdf2483,     0x0d40c0c2,
+    0x4ddfc9cd,     0x0dd8ceaf,     0x4c408ea9,     0x0cdf86bd,
+    0x4d60c1c8,     0x0dffca87,     0x4de3cc7c,     0x4cdd497b,
+    0x0c404950,     0x4d40e595,     0x4ddfeba4,     0x0dd3ed38,
+    0x4cdf046a,     0x0cc9039b,     0x0d60e3d5,     0x0dffe5d7,
+    0x0df4e9a4,     0xba5fd3e3,     0x3a5f03e5,     0xfa411be4,
+    0x7a42cbe2,     0x93df03ff,     0xc820ffff,     0x8822fc7f,
+    0xc8247cbf,     0x88267fff,     0x4e010fe0,     0x4e081fe1,
+    0x4e0c1fe1,     0x4e0a1fe1,     0x4e071fe1,     0x4cc0ac3f,
+    0x1e601000,     0x1e603000,     0x1e621000,     0x1e623000,
+    0x1e641000,     0x1e643000,     0x1e661000,     0x1e663000,
+    0x1e681000,     0x1e683000,     0x1e6a1000,     0x1e6a3000,
+    0x1e6c1000,     0x1e6c3000,     0x1e6e1000,     0x1e6e3000,
+    0x1e701000,     0x1e703000,     0x1e721000,     0x1e723000,
+    0x1e741000,     0x1e743000,     0x1e761000,     0x1e763000,
+    0x1e781000,     0x1e783000,     0x1e7a1000,     0x1e7a3000,
+    0x1e7c1000,     0x1e7c3000,     0x1e7e1000,     0x1e7e3000,
+    0xf8358305,     0xf82d01ed,     0xf8361353,     0xf839234a,
+    0xf82531fb,     0xf8335165,     0xf83a4080,     0xf83673d7,
+    0xf832611c,     0xf8ad837d,     0xf8ab01a5,     0xf8a112b8,
+    0xf8bb2311,     0xf8b230be,     0xf8a75336,     0xf8a4427a,
+    0xf8a6707e,     0xf8b860b7,     0xf8f88392,     0xf8f300ff,
+    0xf8ed1386,     0xf8e822af,     0xf8e2302d,     0xf8f1533d,
+    0xf8f941d2,     0xf8ff7366,     0xf8f061e5,     0xf86b8072,
+    0xf87a0054,     0xf86b1164,     0xf87e22f3,     0xf86331cf,
+    0xf87e5296,     0xf8674305,     0xf87771f0,     0xf86b6013,
+    0xb83c803c,     0xb82b0195,     0xb83d1240,     0xb8252320,
+    0xb82e3340,     0xb83c53b2,     0xb82f43a1,     0xb828739a,
+    0xb831608e,     0xb8b88039,     0xb8aa0231,     0xb8bd12b4,
+    0xb8bd2189,     0xb8ab30a6,     0xb8b552a7,     0xb8aa4197,
+    0xb8b57145,     0xb8be6254,     0xb8ed80b7,     0xb8ef00b8,
+    0xb8e9132a,     0xb8f42231,     0xb8ec33d2,     0xb8e35323,
+    0xb8fa4159,     0xb8e273eb,     0xb8e760a2,     0xb8608287,
+    0xb865005f,     0xb87b1379,     0xb87e2358,     0xb86f32c2,
+    0xb86053e3,     0xb86f4154,     0xb87671d5,     0xb866605e,
+
   };
 // END  Generated code -- do not edit
 
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -306,10 +306,12 @@
 };
 class Post : public PrePost {
   Register _idx;
+  bool _is_postreg;
 public:
-  Post(Register reg, int o) : PrePost(reg, o) { _idx = NULL; }
-  Post(Register reg, Register idx) : PrePost(reg, 0) { _idx = idx; }
+  Post(Register reg, int o) : PrePost(reg, o) { _idx = NULL; _is_postreg = false; }
+  Post(Register reg, Register idx) : PrePost(reg, 0) { _idx = idx; _is_postreg = true; }
   Register idx_reg() { return _idx; }
+  bool is_postreg() {return _is_postreg; }
 };
 
 namespace ext
@@ -393,7 +395,7 @@
     : _base(p.reg()), _offset(p.offset()), _mode(pre) { }
   Address(Post p)
     : _base(p.reg()),  _index(p.idx_reg()), _offset(p.offset()),
-      _mode(p.idx_reg() == NULL ? post : post_reg), _target(0) { }
+      _mode(p.is_postreg() ? post_reg : post), _target(0) { }
   Address(address target, RelocationHolder const& rspec)
     : _mode(literal),
       _rspec(rspec),
@@ -807,32 +809,34 @@
 #undef INSN
 
   // Bitfield
-#define INSN(NAME, opcode)                                              \
+#define INSN(NAME, opcode, size)                                        \
   void NAME(Register Rd, Register Rn, unsigned immr, unsigned imms) {   \
     starti;                                                             \
+    guarantee(size == 1 || (immr < 32 && imms < 32), "incorrect immr/imms");\
     f(opcode, 31, 22), f(immr, 21, 16), f(imms, 15, 10);                \
     zrf(Rn, 5), rf(Rd, 0);                                              \
   }
 
-  INSN(sbfmw, 0b0001001100);
-  INSN(bfmw,  0b0011001100);
-  INSN(ubfmw, 0b0101001100);
-  INSN(sbfm,  0b1001001101);
-  INSN(bfm,   0b1011001101);
-  INSN(ubfm,  0b1101001101);
+  INSN(sbfmw, 0b0001001100, 0);
+  INSN(bfmw,  0b0011001100, 0);
+  INSN(ubfmw, 0b0101001100, 0);
+  INSN(sbfm,  0b1001001101, 1);
+  INSN(bfm,   0b1011001101, 1);
+  INSN(ubfm,  0b1101001101, 1);
 
 #undef INSN
 
   // Extract
-#define INSN(NAME, opcode)                                              \
+#define INSN(NAME, opcode, size)                                        \
   void NAME(Register Rd, Register Rn, Register Rm, unsigned imms) {     \
     starti;                                                             \
+    guarantee(size == 1 || imms < 32, "incorrect imms");                \
     f(opcode, 31, 21), f(imms, 15, 10);                                 \
-    rf(Rm, 16), rf(Rn, 5), rf(Rd, 0);                                   \
+    zrf(Rm, 16), zrf(Rn, 5), zrf(Rd, 0);                                \
   }
 
-  INSN(extrw, 0b00010011100);
-  INSN(extr,  0b10010011110);
+  INSN(extrw, 0b00010011100, 0);
+  INSN(extr,  0b10010011110, 1);
 
 #undef INSN
 
@@ -1126,7 +1130,7 @@
     Register Rn, enum operand_size sz, int op, bool ordered) {
     starti;
     f(sz, 31, 30), f(0b001000, 29, 24), f(op, 23, 21);
-    rf(Rs, 16), f(ordered, 15), rf(Rt2, 10), srf(Rn, 5), zrf(Rt1, 0);
+    rf(Rs, 16), f(ordered, 15), zrf(Rt2, 10), srf(Rn, 5), zrf(Rt1, 0);
   }
 
   void load_exclusive(Register dst, Register addr,
@@ -1255,7 +1259,7 @@
                   enum operand_size sz, int op1, int op2, bool a, bool r) {
     starti;
     f(sz, 31, 30), f(0b111000, 29, 24), f(a, 23), f(r, 22), f(1, 21);
-    rf(Rs, 16), f(op1, 15), f(op2, 14, 12), f(0, 11, 10), srf(Rn, 5), zrf(Rt, 0);
+    zrf(Rs, 16), f(op1, 15), f(op2, 14, 12), f(0, 11, 10), srf(Rn, 5), zrf(Rt, 0);
   }
 
 #define INSN(NAME, NAME_A, NAME_L, NAME_AL, op1, op2)                   \
@@ -1477,6 +1481,7 @@
   void NAME(Register Rd, Register Rn, Register Rm,              \
             enum shift_kind kind = LSL, unsigned shift = 0) {   \
     starti;                                                     \
+    guarantee(size == 1 || shift < 32, "incorrect shift");      \
     f(N, 21);                                                   \
     zrf(Rm, 16), zrf(Rn, 5), zrf(Rd, 0);                        \
     op_shifted_reg(0b01010, kind, shift, size, op);             \
@@ -1539,6 +1544,7 @@
     starti;                                             \
     f(0, 21);                                           \
     assert_cond(kind != ROR);                           \
+    guarantee(size == 1 || shift < 32, "incorrect shift");\
     zrf(Rd, 0), zrf(Rn, 5), zrf(Rm, 16);                \
     op_shifted_reg(0b01011, kind, shift, size, op);     \
   }
@@ -1567,7 +1573,7 @@
   void add_sub_extended_reg(unsigned op, unsigned decode,
     Register Rd, Register Rn, Register Rm,
     unsigned opt, ext::operation option, unsigned imm) {
-    guarantee(imm <= 4, "shift amount must be < 4");
+    guarantee(imm <= 4, "shift amount must be <= 4");
     f(op, 31, 29), f(decode, 28, 24), f(opt, 23, 22), f(1, 21);
     f(option, 15, 13), f(imm, 12, 10);
   }
@@ -1652,7 +1658,7 @@
     f(o2, 10);
     f(o3, 4);
     f(nzcv, 3, 0);
-    f(imm5, 20, 16), rf(Rn, 5);
+    f(imm5, 20, 16), zrf(Rn, 5);
   }
 
 #define INSN(NAME, op)                                                  \
@@ -2121,7 +2127,12 @@
   }
   void ld_st(FloatRegister Vt, SIMD_Arrangement T, Register Xn,
              int imm, int op1, int op2, int regs) {
-    guarantee(T <= T1Q && imm == SIMD_Size_in_bytes[T] * regs, "bad offset");
+
+    bool replicate = op2 >> 2 == 3;
+    // post-index value (imm) is formed differently for replicate/non-replicate ld* instructions
+    int expectedImmediate = replicate ? regs * (1 << (T >> 1)) : SIMD_Size_in_bytes[T] * regs;
+    guarantee(T < T1Q , "incorrect arrangement");
+    guarantee(imm == expectedImmediate, "bad offset");
     starti;
     f(0,31), f((int)T & 1, 30);
     f(op1 | 0b100, 29, 21), f(0b11111, 20, 16), f(op2, 15, 12);
@@ -2228,42 +2239,47 @@
 
 #undef INSN
 
-#define INSN(NAME, opc, opc2)                                                                 \
+#define INSN(NAME, opc, opc2, acceptT2D)                                                \
   void NAME(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn, FloatRegister Vm) { \
+    guarantee(T != T1Q && T != T1D, "incorrect arrangement");                           \
+    if (!acceptT2D) guarantee(T != T2D, "incorrect arrangement");                       \
     starti;                                                                             \
     f(0, 31), f((int)T & 1, 30), f(opc, 29), f(0b01110, 28, 24);                        \
     f((int)T >> 1, 23, 22), f(1, 21), rf(Vm, 16), f(opc2, 15, 10);                      \
     rf(Vn, 5), rf(Vd, 0);                                                               \
   }
 
-  INSN(addv,   0, 0b100001);
-  INSN(subv,   1, 0b100001);
-  INSN(mulv,   0, 0b100111);
-  INSN(mlav,   0, 0b100101);
-  INSN(mlsv,   1, 0b100101);
-  INSN(sshl,   0, 0b010001);
-  INSN(ushl,   1, 0b010001);
-  INSN(umullv, 1, 0b110000);
-  INSN(umlalv, 1, 0b100000);
+  INSN(addv,   0, 0b100001, true);  // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S, T2D
+  INSN(subv,   1, 0b100001, true);  // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S, T2D
+  INSN(mulv,   0, 0b100111, false); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S
+  INSN(mlav,   0, 0b100101, false); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S
+  INSN(mlsv,   1, 0b100101, false); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S
+  INSN(sshl,   0, 0b010001, true);  // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S, T2D
+  INSN(ushl,   1, 0b010001, true);  // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S, T2D
+  INSN(umullv, 1, 0b110000, false); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S
+  INSN(umlalv, 1, 0b100000, false); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S
 
 #undef INSN
 
-#define INSN(NAME, opc, opc2) \
+#define INSN(NAME, opc, opc2, accepted) \
   void NAME(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn) {                   \
+    guarantee(T != T1Q && T != T1D, "incorrect arrangement");                           \
+    if (accepted < 2) guarantee(T != T2S && T != T2D, "incorrect arrangement");         \
+    if (accepted == 0) guarantee(T == T8B || T == T16B, "incorrect arrangement");       \
     starti;                                                                             \
     f(0, 31), f((int)T & 1, 30), f(opc, 29), f(0b01110, 28, 24);                        \
     f((int)T >> 1, 23, 22), f(opc2, 21, 10);                                            \
     rf(Vn, 5), rf(Vd, 0);                                                               \
   }
 
-  INSN(absr,   0, 0b100000101110);
-  INSN(negr,   1, 0b100000101110);
-  INSN(notr,   1, 0b100000010110);
-  INSN(addv,   0, 0b110001101110);
-  INSN(cls,    0, 0b100000010010);
-  INSN(clz,    1, 0b100000010010);
-  INSN(cnt,    0, 0b100000010110);
-  INSN(uaddlv, 1, 0b110000001110);
+  INSN(absr,   0, 0b100000101110, 1); // accepted arrangements: T8B, T16B, T4H, T8H,      T4S
+  INSN(negr,   1, 0b100000101110, 2); // accepted arrangements: T8B, T16B, T4H, T8H, T2S, T4S, T2D
+  INSN(notr,   1, 0b100000010110, 0); // accepted arrangements: T8B, T16B
+  INSN(addv,   0, 0b110001101110, 1); // accepted arrangements: T8B, T16B, T4H, T8H,      T4S
+  INSN(cls,    0, 0b100000010010, 1); // accepted arrangements: T8B, T16B, T4H, T8H,      T4S
+  INSN(clz,    1, 0b100000010010, 1); // accepted arrangements: T8B, T16B, T4H, T8H,      T4S
+  INSN(cnt,    0, 0b100000010110, 0); // accepted arrangements: T8B, T16B
+  INSN(uaddlv, 1, 0b110000001110, 1); // accepted arrangements: T8B, T16B, T4H, T8H,      T4S
 
 #undef INSN
 
@@ -2287,7 +2303,7 @@
     starti;                                                                            \
     assert(lsl == 0 ||                                                                 \
            ((T == T4H || T == T8H) && lsl == 8) ||                                     \
-           ((T == T2S || T == T4S) && ((lsl >> 3) < 4)), "invalid shift");             \
+           ((T == T2S || T == T4S) && ((lsl >> 3) < 4) && ((lsl & 7) == 0)), "invalid shift");\
     cmode |= lsl >> 2;                                                                 \
     if (T == T4H || T == T8H) cmode |= 0b1000;                                         \
     if (!(T == T4H || T == T8H || T == T2S || T == T4S)) {                             \
@@ -2448,7 +2464,8 @@
 
 #undef INSN
 
-  void ushll(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, SIMD_Arrangement Tb, int shift) {
+private:
+  void _ushll(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, SIMD_Arrangement Tb, int shift) {
     starti;
     /* The encodings for the immh:immb fields (bits 22:16) are
      *   0001 xxx       8H, 8B/16b shift = xxx
@@ -2461,8 +2478,16 @@
     f(0, 31), f(Tb & 1, 30), f(0b1011110, 29, 23), f((1 << ((Tb>>1)+3))|shift, 22, 16);
     f(0b101001, 15, 10), rf(Vn, 5), rf(Vd, 0);
   }
+
+public:
+  void ushll(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn,  SIMD_Arrangement Tb, int shift) {
+    assert(Tb == T8B || Tb == T4H || Tb == T2S, "invalid arrangement");
+    _ushll(Vd, Ta, Vn, Tb, shift);
+  }
+
   void ushll2(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn,  SIMD_Arrangement Tb, int shift) {
-    ushll(Vd, Ta, Vn, Tb, shift);
+    assert(Tb == T16B || Tb == T8H || Tb == T4S, "invalid arrangement");
+    _ushll(Vd, Ta, Vn, Tb, shift);
   }
 
   // Move from general purpose register
@@ -2470,19 +2495,21 @@
   void mov(FloatRegister Vd, SIMD_Arrangement T, int index, Register Xn) {
     starti;
     f(0b01001110000, 31, 21), f(((1 << (T >> 1)) | (index << ((T >> 1) + 1))), 20, 16);
-    f(0b000111, 15, 10), rf(Xn, 5), rf(Vd, 0);
+    f(0b000111, 15, 10), zrf(Xn, 5), rf(Vd, 0);
   }
 
   // Move to general purpose register
   //   mov  Rd, Vn.T[index]
   void mov(Register Xd, FloatRegister Vn, SIMD_Arrangement T, int index) {
+    guarantee(T >= T2S && T < T1Q, "only D and S arrangements are supported");
     starti;
     f(0, 31), f((T >= T1D) ? 1:0, 30), f(0b001110000, 29, 21);
     f(((1 << (T >> 1)) | (index << ((T >> 1) + 1))), 20, 16);
     f(0b001111, 15, 10), rf(Vn, 5), rf(Xd, 0);
   }
 
-  void pmull(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, FloatRegister Vm, SIMD_Arrangement Tb) {
+private:
+  void _pmull(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, FloatRegister Vm, SIMD_Arrangement Tb) {
     starti;
     assert((Ta == T1Q && (Tb == T1D || Tb == T2D)) ||
            (Ta == T8H && (Tb == T8B || Tb == T16B)), "Invalid Size specifier");
@@ -2490,9 +2517,16 @@
     f(0, 31), f(Tb & 1, 30), f(0b001110, 29, 24), f(size, 23, 22);
     f(1, 21), rf(Vm, 16), f(0b111000, 15, 10), rf(Vn, 5), rf(Vd, 0);
   }
+
+public:
+  void pmull(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, FloatRegister Vm, SIMD_Arrangement Tb) {
+    assert(Tb == T1D || Tb == T8B, "pmull assumes T1D or T8B as the second size specifier");
+    _pmull(Vd, Ta, Vn, Vm, Tb);
+  }
+
   void pmull2(FloatRegister Vd, SIMD_Arrangement Ta, FloatRegister Vn, FloatRegister Vm, SIMD_Arrangement Tb) {
     assert(Tb == T2D || Tb == T16B, "pmull2 assumes T2D or T16B as the second size specifier");
-    pmull(Vd, Ta, Vn, Vm, Tb);
+    _pmull(Vd, Ta, Vn, Vm, Tb);
   }
 
   void uqxtn(FloatRegister Vd, SIMD_Arrangement Tb, FloatRegister Vn, SIMD_Arrangement Ta) {
@@ -2509,7 +2543,7 @@
     starti;
     assert(T != T1D, "reserved encoding");
     f(0,31), f((int)T & 1, 30), f(0b001110000, 29, 21);
-    f((1 << (T >> 1)), 20, 16), f(0b000011, 15, 10), rf(Xs, 5), rf(Vd, 0);
+    f((1 << (T >> 1)), 20, 16), f(0b000011, 15, 10), zrf(Xs, 5), rf(Vd, 0);
   }
 
   void dup(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn, int index = 0)
@@ -2524,6 +2558,7 @@
   // AdvSIMD ZIP/UZP/TRN
 #define INSN(NAME, opcode)                                              \
   void NAME(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn, FloatRegister Vm) { \
+    guarantee(T != T1D && T != T1Q, "invalid arrangement");             \
     starti;                                                             \
     f(0, 31), f(0b001110, 29, 24), f(0, 21), f(0, 15);                  \
     f(opcode, 14, 12), f(0b10, 11, 10);                                 \
--- a/src/hotspot/cpu/aarch64/register_aarch64.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/aarch64/register_aarch64.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -136,7 +136,7 @@
   VMReg as_VMReg();
 
   // derived registers, offsets, and addresses
-  FloatRegister successor() const                          { return as_FloatRegister(encoding() + 1); }
+  FloatRegister successor() const                          { return as_FloatRegister((encoding() + 1) % 32); }
 
   // accessors
   int   encoding() const                          { assert(is_valid(), "invalid register"); return (intptr_t)this; }
--- a/src/hotspot/cpu/ppc/c1_LIRAssembler_ppc.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/c1_LIRAssembler_ppc.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -80,7 +80,19 @@
 }
 
 void LIR_Assembler::clinit_barrier(ciMethod* method) {
-  ShouldNotReachHere(); // not implemented
+  assert(!method->holder()->is_not_initialized(), "initialization should have been started");
+
+  Label L_skip_barrier;
+  Register klass = R20;
+
+  metadata2reg(method->holder()->constant_encoding(), klass);
+  __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
+
+  __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
+  __ mtctr(klass);
+  __ bctr();
+
+  __ bind(L_skip_barrier);
 }
 
 void LIR_Assembler::osr_entry() {
--- a/src/hotspot/cpu/ppc/interp_masm_ppc.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/interp_masm_ppc.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -82,6 +82,8 @@
   // load cpool->resolved_klass_at(index)
   void load_resolved_klass_at_offset(Register Rcpool, Register Roffset, Register Rklass);
 
+  void load_resolved_method_at_index(int byte_no, Register cache, Register method);
+
   void load_receiver(Register Rparam_count, Register Rrecv_dst);
 
   // helpers for expression stack
--- a/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -516,6 +516,18 @@
   ldx(Rklass, Rklass, Roffset);
 }
 
+void InterpreterMacroAssembler::load_resolved_method_at_index(int byte_no,
+                                                              Register cache,
+                                                              Register method) {
+  const int method_offset = in_bytes(
+    ConstantPoolCache::base_offset() +
+      ((byte_no == TemplateTable::f2_byte)
+       ? ConstantPoolCacheEntry::f2_offset()
+       : ConstantPoolCacheEntry::f1_offset()));
+
+  ld(method, method_offset, cache); // get f1 Method*
+}
+
 // Generate a subtype check: branch to ok_is_subtype if sub_klass is
 // a subtype of super_klass. Blows registers Rsub_klass, tmp1, tmp2.
 void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass, Register Rsuper_klass, Register Rtmp1,
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2011,6 +2011,35 @@
   bind(L_failure); // Fallthru if not successful.
 }
 
+void MacroAssembler::clinit_barrier(Register klass, Register thread, Label* L_fast_path, Label* L_slow_path) {
+  assert(L_fast_path != NULL || L_slow_path != NULL, "at least one is required");
+
+  Label L_fallthrough;
+  if (L_fast_path == NULL) {
+    L_fast_path = &L_fallthrough;
+  } else if (L_slow_path == NULL) {
+    L_slow_path = &L_fallthrough;
+  }
+
+  // Fast path check: class is fully initialized
+  lbz(R0, in_bytes(InstanceKlass::init_state_offset()), klass);
+  cmpwi(CCR0, R0, InstanceKlass::fully_initialized);
+  beq(CCR0, *L_fast_path);
+
+  // Fast path check: current thread is initializer thread
+  ld(R0, in_bytes(InstanceKlass::init_thread_offset()), klass);
+  cmpd(CCR0, thread, R0);
+  if (L_slow_path == &L_fallthrough) {
+    beq(CCR0, *L_fast_path);
+  } else if (L_fast_path == &L_fallthrough) {
+    bne(CCR0, *L_slow_path);
+  } else {
+    Unimplemented();
+  }
+
+  bind(L_fallthrough);
+}
+
 void MacroAssembler::check_method_handle_type(Register mtype_reg, Register mh_reg,
                                               Register temp_reg,
                                               Label& wrong_method_type) {
@@ -3194,6 +3223,12 @@
   resolve_oop_handle(mirror);
 }
 
+void MacroAssembler::load_method_holder(Register holder, Register method) {
+  ld(holder, in_bytes(Method::const_offset()), method);
+  ld(holder, in_bytes(ConstMethod::constants_offset()), holder);
+  ld(holder, ConstantPool::pool_holder_offset_in_bytes(), holder);
+}
+
 // Clear Array
 // For very short arrays. tmp == R0 is allowed.
 void MacroAssembler::clear_memory_unrolled(Register base_ptr, int cnt_dwords, Register tmp, int offset) {
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -559,6 +559,11 @@
                            Register temp2_reg,
                            Label& L_success);
 
+  void clinit_barrier(Register klass,
+                      Register thread,
+                      Label* L_fast_path = NULL,
+                      Label* L_slow_path = NULL);
+
   // Method handle support (JSR 292).
   void check_method_handle_type(Register mtype_reg, Register mh_reg, Register temp_reg, Label& wrong_method_type);
 
@@ -722,6 +727,7 @@
 
   void resolve_oop_handle(Register result);
   void load_mirror_from_const_method(Register mirror, Register const_method);
+  void load_method_holder(Register holder, Register method);
 
   static int instr_size_for_decode_klass_not_null();
   void decode_klass_not_null(Register dst, Register src = noreg);
--- a/src/hotspot/cpu/ppc/ppc.ad	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/ppc.ad	Wed Jun 12 10:02:49 2019 +0530
@@ -1400,6 +1400,24 @@
     ___(mflr) mflr(return_pc);
   }
 
+  if (C->clinit_barrier_on_entry()) {
+    assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
+
+    Label L_skip_barrier;
+    Register klass = toc_temp;
+
+    // Notify OOP recorder (don't need the relocation)
+    AddressLiteral md = __ constant_metadata_address(C->method()->holder()->constant_encoding());
+    __ load_const_optimized(klass, md.value(), R0);
+    __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
+
+    __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
+    __ mtctr(klass);
+    __ bctr();
+
+    __ bind(L_skip_barrier);
+  }
+
   // Calls to C2R adapters often do not accept exceptional returns.
   // We require that their callers must bang for them. But be
   // careful, because some VM calls (such as call site linkage) can
--- a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1274,7 +1274,30 @@
 
   // entry: c2i
 
-  c2i_entry = gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, call_interpreter, ientry);
+  c2i_entry = __ pc();
+
+  // Class initialization barrier for static methods
+  if (VM_Version::supports_fast_class_init_checks()) {
+    Label L_skip_barrier;
+
+    { // Bypass the barrier for non-static methods
+      __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
+      __ andi_(R0, R0, JVM_ACC_STATIC);
+      __ beq(CCR0, L_skip_barrier); // non-static
+    }
+
+    Register klass = R11_scratch1;
+    __ load_method_holder(klass, R19_method);
+    __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
+
+    __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
+    __ mtctr(klass);
+    __ bctr();
+
+    __ bind(L_skip_barrier);
+  }
+
+  gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, call_interpreter, ientry);
 
   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 }
@@ -2106,6 +2129,21 @@
     __ tabort_();
   }
 
+  if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
+    Label L_skip_barrier;
+    Register klass = r_temp_1;
+    // Notify OOP recorder (don't need the relocation)
+    AddressLiteral md = __ constant_metadata_address(method->method_holder());
+    __ load_const_optimized(klass, md.value(), R0);
+    __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
+
+    __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
+    __ mtctr(klass);
+    __ bctr();
+
+    __ bind(L_skip_barrier);
+  }
+
   __ save_LR_CR(r_temp_1);
   __ generate_stack_overflow_check(frame_size_in_bytes); // Check before creating frame.
   __ mr(r_callers_sp, R1_SP);                            // Remember frame pointer.
--- a/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2232,7 +2232,7 @@
 void TemplateTable::resolve_cache_and_index(int byte_no, Register Rcache, Register Rscratch, size_t index_size) {
 
   __ get_cache_and_index_at_bcp(Rcache, 1, index_size);
-  Label Lresolved, Ldone;
+  Label Lresolved, Ldone, L_clinit_barrier_slow;
 
   Bytecodes::Code code = bytecode();
   switch (code) {
@@ -2253,6 +2253,9 @@
   __ cmpdi(CCR0, Rscratch, (int)code);
   __ beq(CCR0, Lresolved);
 
+  // Class initialization barrier slow path lands here as well.
+  __ bind(L_clinit_barrier_slow);
+
   address entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_from_cache);
   __ li(R4_ARG2, code);
   __ call_VM(noreg, entry, R4_ARG2, true);
@@ -2263,6 +2266,17 @@
 
   __ bind(Lresolved);
   __ isync(); // Order load wrt. succeeding loads.
+
+  // Class initialization barrier for static methods
+  if (VM_Version::supports_fast_class_init_checks() && bytecode() == Bytecodes::_invokestatic) {
+    const Register method = Rscratch;
+    const Register klass  = Rscratch;
+
+    __ load_resolved_method_at_index(byte_no, Rcache, method);
+    __ load_method_holder(klass, method);
+    __ clinit_barrier(klass, R16_thread, NULL /*L_fast_path*/, &L_clinit_barrier_slow);
+  }
+
   __ bind(Ldone);
 }
 
@@ -2329,7 +2343,7 @@
     // Already resolved.
     __ get_cache_and_index_at_bcp(Rcache, 1);
   } else {
-    resolve_cache_and_index(byte_no, Rcache, R0, is_invokedynamic ? sizeof(u4) : sizeof(u2));
+    resolve_cache_and_index(byte_no, Rcache, /* temp */ Rmethod, is_invokedynamic ? sizeof(u4) : sizeof(u2));
   }
 
   __ ld(Rmethod, method_offset, Rcache);
@@ -3634,9 +3648,7 @@
   // Find entry point to call.
 
   // Get declaring interface class from method
-  __ ld(Rinterface_klass, in_bytes(Method::const_offset()), Rmethod);
-  __ ld(Rinterface_klass, in_bytes(ConstMethod::constants_offset()), Rinterface_klass);
-  __ ld(Rinterface_klass, ConstantPool::pool_holder_offset_in_bytes(), Rinterface_klass);
+  __ load_method_holder(Rinterface_klass, Rmethod);
 
   // Get itable index from method
   __ lwa(Rindex, in_bytes(Method::itable_index_offset()), Rmethod);
--- a/src/hotspot/cpu/ppc/vm_version_ppc.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/ppc/vm_version_ppc.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -95,6 +95,9 @@
   // Override Abstract_VM_Version implementation
   static bool use_biased_locking();
 
+  // PPC64 supports fast class initialization checks for static methods.
+  static bool supports_fast_class_init_checks() { return true; }
+
   static bool is_determine_features_test_running() { return _is_determine_features_test_running; }
   // CPU instruction support
   static bool has_fsqrt()   { return (_features & fsqrt_m) != 0; }
--- a/src/hotspot/cpu/x86/gc/z/z_x86_64.ad	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/x86/gc/z/z_x86_64.ad	Wed Jun 12 10:02:49 2019 +0530
@@ -21,6 +21,12 @@
 // questions.
 //
 
+source_hpp %{
+
+#include "gc/z/c2/zBarrierSetC2.hpp"
+
+%}
+
 source %{
 
 #include "gc/z/zBarrierSetAssembler.hpp"
@@ -45,7 +51,7 @@
                                       rxmm12 x12, rxmm13 x13, rxmm14 x14, rxmm15 x15) %{
 
   match(Set dst (LoadBarrierSlowReg src));
-  predicate(UseAVX <= 2);
+  predicate((UseAVX <= 2) && !n->as_LoadBarrierSlowReg()->is_weak());
 
   effect(DEF dst, KILL cr,
          KILL x0, KILL x1, KILL x2, KILL x3,
@@ -74,7 +80,7 @@
                                 rxmm28 x28, rxmm29 x29, rxmm30 x30, rxmm31 x31) %{
 
   match(Set dst (LoadBarrierSlowReg src));
-  predicate(UseAVX == 3);
+  predicate((UseAVX == 3) && !n->as_LoadBarrierSlowReg()->is_weak());
 
   effect(DEF dst, KILL cr,
          KILL x0, KILL x1, KILL x2, KILL x3,
@@ -102,8 +108,8 @@
                                           rxmm8 x8, rxmm9 x9, rxmm10 x10, rxmm11 x11,
                                           rxmm12 x12, rxmm13 x13, rxmm14 x14, rxmm15 x15) %{
 
-  match(Set dst (LoadBarrierWeakSlowReg src));
-  predicate(UseAVX <= 2);
+  match(Set dst (LoadBarrierSlowReg src));
+  predicate((UseAVX <= 2) && n->as_LoadBarrierSlowReg()->is_weak());
 
   effect(DEF dst, KILL cr,
          KILL x0, KILL x1, KILL x2, KILL x3,
@@ -131,8 +137,8 @@
                                     rxmm24 x24, rxmm25 x25, rxmm26 x26, rxmm27 x27,
                                     rxmm28 x28, rxmm29 x29, rxmm30 x30, rxmm31 x31) %{
 
-  match(Set dst (LoadBarrierWeakSlowReg src));
-  predicate(UseAVX == 3);
+  match(Set dst (LoadBarrierSlowReg src));
+  predicate((UseAVX == 3) && n->as_LoadBarrierSlowReg()->is_weak());
 
   effect(DEF dst, KILL cr,
          KILL x0, KILL x1, KILL x2, KILL x3,
@@ -152,3 +158,58 @@
 
   ins_pipe(pipe_slow);
 %}
+
+// Specialized versions of compareAndExchangeP that adds a keepalive that is consumed
+// but doesn't affect output.
+
+instruct z_compareAndExchangeP(
+        memory mem_ptr,
+        rax_RegP oldval, rRegP newval, rRegP keepalive,
+        rFlagsReg cr) %{
+    predicate(VM_Version::supports_cx8());
+    match(Set oldval (ZCompareAndExchangeP (Binary mem_ptr keepalive) (Binary oldval newval)));
+    effect(KILL cr);
+
+    format %{ "cmpxchgq $mem_ptr,$newval\t# "
+              "If rax == $mem_ptr then store $newval into $mem_ptr\n\t" %}
+    opcode(0x0F, 0xB1);
+    ins_encode(lock_prefix,
+            REX_reg_mem_wide(newval, mem_ptr),
+            OpcP, OpcS,
+            reg_mem(newval, mem_ptr)  // lock cmpxchg
+    );
+    ins_pipe( pipe_cmpxchg );
+%}
+
+instruct z_compareAndSwapP(rRegI res,
+                         memory mem_ptr,
+                         rax_RegP oldval, rRegP newval, rRegP keepalive,
+                         rFlagsReg cr) %{
+  predicate(VM_Version::supports_cx8());
+  match(Set res (ZCompareAndSwapP (Binary mem_ptr keepalive) (Binary oldval newval)));
+  match(Set res (ZWeakCompareAndSwapP (Binary mem_ptr keepalive) (Binary oldval newval)));
+  effect(KILL cr, KILL oldval);
+
+  format %{ "cmpxchgq $mem_ptr,$newval\t# "
+            "If rax == $mem_ptr then store $newval into $mem_ptr\n\t"
+            "sete    $res\n\t"
+            "movzbl  $res, $res" %}
+  opcode(0x0F, 0xB1);
+  ins_encode(lock_prefix,
+          REX_reg_mem_wide(newval, mem_ptr),
+          OpcP, OpcS,
+          reg_mem(newval, mem_ptr),
+          REX_breg(res), Opcode(0x0F), Opcode(0x94), reg(res), // sete
+          REX_reg_breg(res, res), // movzbl
+          Opcode(0xF), Opcode(0xB6), reg_reg(res, res));
+  ins_pipe( pipe_cmpxchg );
+%}
+
+instruct z_xchgP( memory mem, rRegP newval, rRegP keepalive) %{
+  match(Set newval (ZGetAndSetP mem (Binary newval keepalive)));
+  format %{ "XCHGQ  $newval,[$mem]" %}
+  ins_encode %{
+    __ xchgq($newval$$Register, $mem$$Address);
+  %}
+  ins_pipe( pipe_cmpxchg );
+%}
--- a/src/hotspot/cpu/x86/x86.ad	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/cpu/x86/x86.ad	Wed Jun 12 10:02:49 2019 +0530
@@ -8358,7 +8358,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp, TEMP scratch);
   format %{"vextendbw $tmp,$src\n\t"
            "vshiftw   $tmp,$shift\n\t"
            "movdqu    $dst,[0x00ff00ff0x00ff00ff]\n\t"
@@ -8381,7 +8381,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp, TEMP scratch);
   format %{"vextendbw $tmp,$src\n\t"
            "vshiftw   $tmp,$shift\n\t"
            "movdqu    $dst,[0x00ff00ff0x00ff00ff]\n\t"
@@ -8404,7 +8404,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp1, TEMP tmp2, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp1, TEMP tmp2, TEMP scratch);
   format %{"vextendbw $tmp1,$src\n\t"
            "vshiftw   $tmp1,$shift\n\t"
            "pshufd    $tmp2,$src\n\t"
@@ -8435,7 +8435,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp, TEMP scratch);
   format %{"vextendbw  $tmp,$src\n\t"
            "vshiftw    $tmp,$tmp,$shift\n\t"
            "vpand      $tmp,$tmp,[0x00ff00ff0x00ff00ff]\n\t"
@@ -8459,7 +8459,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp, TEMP scratch);
   format %{"vextracti128_high  $tmp,$src\n\t"
            "vextendbw  $tmp,$tmp\n\t"
            "vextendbw  $dst,$src\n\t"
@@ -8491,7 +8491,7 @@
   match(Set dst (LShiftVB src shift));
   match(Set dst (RShiftVB src shift));
   match(Set dst (URShiftVB src shift));
-  effect(TEMP dst, TEMP tmp1, TEMP tmp2, TEMP scratch);
+  effect(TEMP dst, USE src, USE shift, TEMP tmp1, TEMP tmp2, TEMP scratch);
   format %{"vextracti64x4  $tmp1,$src\n\t"
            "vextendbw      $tmp1,$tmp1\n\t"
            "vextendbw      $tmp2,$src\n\t"
@@ -8534,6 +8534,7 @@
   match(Set dst (LShiftVS src shift));
   match(Set dst (RShiftVS src shift));
   match(Set dst (URShiftVS src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftw  $dst,$src,$shift\t! shift packed2S" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8554,6 +8555,7 @@
   match(Set dst (LShiftVS src shift));
   match(Set dst (RShiftVS src shift));
   match(Set dst (URShiftVS src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftw  $dst,$src,$shift\t! shift packed4S" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8575,6 +8577,7 @@
   match(Set dst (LShiftVS src shift));
   match(Set dst (RShiftVS src shift));
   match(Set dst (URShiftVS src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftw  $dst,$src,$shift\t! shift packed8S" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8595,6 +8598,7 @@
   match(Set dst (LShiftVS src shift));
   match(Set dst (RShiftVS src shift));
   match(Set dst (URShiftVS src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftw  $dst,$src,$shift\t! shift packed16S" %}
   ins_encode %{
     int vector_len = 1;
@@ -8609,6 +8613,7 @@
   match(Set dst (LShiftVS src shift));
   match(Set dst (RShiftVS src shift));
   match(Set dst (URShiftVS src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftw  $dst,$src,$shift\t! shift packed32S" %}
   ins_encode %{
     int vector_len = 2;
@@ -8624,6 +8629,7 @@
   match(Set dst (LShiftVI src shift));
   match(Set dst (RShiftVI src shift));
   match(Set dst (URShiftVI src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftd  $dst,$src,$shift\t! shift packed2I" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8644,6 +8650,7 @@
   match(Set dst (LShiftVI src shift));
   match(Set dst (RShiftVI src shift));
   match(Set dst (URShiftVI src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftd  $dst,$src,$shift\t! shift packed4I" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8664,6 +8671,7 @@
   match(Set dst (LShiftVI src shift));
   match(Set dst (RShiftVI src shift));
   match(Set dst (URShiftVI src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftd  $dst,$src,$shift\t! shift packed8I" %}
   ins_encode %{
     int vector_len = 1;
@@ -8678,6 +8686,7 @@
   match(Set dst (LShiftVI src shift));
   match(Set dst (RShiftVI src shift));
   match(Set dst (URShiftVI src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftd  $dst,$src,$shift\t! shift packed16I" %}
   ins_encode %{
     int vector_len = 2;
@@ -8692,6 +8701,7 @@
   predicate(n->as_Vector()->length() == 2);
   match(Set dst (LShiftVL src shift));
   match(Set dst (URShiftVL src shift));
+  effect(TEMP dst, USE src, USE shift);
   format %{ "vshiftq  $dst,$src,$shift\t! shift packed2L" %}
   ins_encode %{
     int opcode = this->as_Mach()->ideal_Opcode();
@@ -8711,6 +8721,7 @@
   predicate(UseAVX > 1 && n->as_Vector()->length() == 4);
   match(Set dst (LShiftVL src shift));
   match(Set dst (URShiftVL src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftq  $dst,$src,$shift\t! left shift packed4L" %}
   ins_encode %{
     int vector_len = 1;
@@ -8725,6 +8736,7 @@
   match(Set dst (LShiftVL src shift));
   match(Set dst (RShiftVL src shift));
   match(Set dst (URShiftVL src shift));
+  effect(DEF dst, USE src, USE shift);
   format %{ "vshiftq  $dst,$src,$shift\t! shift packed8L" %}
   ins_encode %{
     int vector_len = 2;
--- a/src/hotspot/os/bsd/os_bsd.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/os/bsd/os_bsd.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2189,11 +2189,6 @@
 // available (and not reserved for something else).
 
 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
-  const int max_tries = 10;
-  char* base[max_tries];
-  size_t size[max_tries];
-  const size_t gap = 0x000000;
-
   // Assert only that the size is a multiple of the page size, since
   // that's all that mmap requires, and since that's all we really know
   // about at this low abstraction level.  If we need higher alignment,
@@ -2216,50 +2211,7 @@
     anon_munmap(addr, bytes);
   }
 
-  int i;
-  for (i = 0; i < max_tries; ++i) {
-    base[i] = reserve_memory(bytes);
-
-    if (base[i] != NULL) {
-      // Is this the block we wanted?
-      if (base[i] == requested_addr) {
-        size[i] = bytes;
-        break;
-      }
-
-      // Does this overlap the block we wanted? Give back the overlapped
-      // parts and try again.
-
-      size_t top_overlap = requested_addr + (bytes + gap) - base[i];
-      if (top_overlap >= 0 && top_overlap < bytes) {
-        unmap_memory(base[i], top_overlap);
-        base[i] += top_overlap;
-        size[i] = bytes - top_overlap;
-      } else {
-        size_t bottom_overlap = base[i] + bytes - requested_addr;
-        if (bottom_overlap >= 0 && bottom_overlap < bytes) {
-          unmap_memory(requested_addr, bottom_overlap);
-          size[i] = bytes - bottom_overlap;
-        } else {
-          size[i] = bytes;
-        }
-      }
-    }
-  }
-
-  // Give back the unused reserved pieces.
-
-  for (int j = 0; j < i; ++j) {
-    if (base[j] != NULL) {
-      unmap_memory(base[j], size[j]);
-    }
-  }
-
-  if (i < max_tries) {
-    return requested_addr;
-  } else {
-    return NULL;
-  }
+  return NULL;
 }
 
 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
--- a/src/hotspot/os/linux/os_linux.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/os/linux/os_linux.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -4105,11 +4105,6 @@
 // available (and not reserved for something else).
 
 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
-  const int max_tries = 10;
-  char* base[max_tries];
-  size_t size[max_tries];
-  const size_t gap = 0x000000;
-
   // Assert only that the size is a multiple of the page size, since
   // that's all that mmap requires, and since that's all we really know
   // about at this low abstraction level.  If we need higher alignment,
@@ -4132,50 +4127,7 @@
     anon_munmap(addr, bytes);
   }
 
-  int i;
-  for (i = 0; i < max_tries; ++i) {
-    base[i] = reserve_memory(bytes);
-
-    if (base[i] != NULL) {
-      // Is this the block we wanted?
-      if (base[i] == requested_addr) {
-        size[i] = bytes;
-        break;
-      }
-
-      // Does this overlap the block we wanted? Give back the overlapped
-      // parts and try again.
-
-      ptrdiff_t top_overlap = requested_addr + (bytes + gap) - base[i];
-      if (top_overlap >= 0 && (size_t)top_overlap < bytes) {
-        unmap_memory(base[i], top_overlap);
-        base[i] += top_overlap;
-        size[i] = bytes - top_overlap;
-      } else {
-        ptrdiff_t bottom_overlap = base[i] + bytes - requested_addr;
-        if (bottom_overlap >= 0 && (size_t)bottom_overlap < bytes) {
-          unmap_memory(requested_addr, bottom_overlap);
-          size[i] = bytes - bottom_overlap;
-        } else {
-          size[i] = bytes;
-        }
-      }
-    }
-  }
-
-  // Give back the unused reserved pieces.
-
-  for (int j = 0; j < i; ++j) {
-    if (base[j] != NULL) {
-      unmap_memory(base[j], size[j]);
-    }
-  }
-
-  if (i < max_tries) {
-    return requested_addr;
-  } else {
-    return NULL;
-  }
+  return NULL;
 }
 
 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
--- a/src/hotspot/os/solaris/os_solaris.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/os/solaris/os_solaris.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2553,17 +2553,6 @@
 // available (and not reserved for something else).
 
 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
-  const int max_tries = 10;
-  char* base[max_tries];
-  size_t size[max_tries];
-
-  // Solaris adds a gap between mmap'ed regions.  The size of the gap
-  // is dependent on the requested size and the MMU.  Our initial gap
-  // value here is just a guess and will be corrected later.
-  bool had_top_overlap = false;
-  bool have_adjusted_gap = false;
-  size_t gap = 0x400000;
-
   // Assert only that the size is a multiple of the page size, since
   // that's all that mmap requires, and since that's all we really know
   // about at this low abstraction level.  If we need higher alignment,
@@ -2572,105 +2561,18 @@
   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
 
   // Since snv_84, Solaris attempts to honor the address hint - see 5003415.
-  // Give it a try, if the kernel honors the hint we can return immediately.
   char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);
 
   volatile int err = errno;
   if (addr == requested_addr) {
     return addr;
-  } else if (addr != NULL) {
+  }
+
+  if (addr != NULL) {
     pd_unmap_memory(addr, bytes);
   }
 
-  if (log_is_enabled(Warning, os)) {
-    char buf[256];
-    buf[0] = '\0';
-    if (addr == NULL) {
-      jio_snprintf(buf, sizeof(buf), ": %s", os::strerror(err));
-    }
-    log_info(os)("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "
-            PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT
-            "%s", bytes, requested_addr, addr, buf);
-  }
-
-  // Address hint method didn't work.  Fall back to the old method.
-  // In theory, once SNV becomes our oldest supported platform, this
-  // code will no longer be needed.
-  //
-  // Repeatedly allocate blocks until the block is allocated at the
-  // right spot. Give up after max_tries.
-  int i;
-  for (i = 0; i < max_tries; ++i) {
-    base[i] = reserve_memory(bytes);
-
-    if (base[i] != NULL) {
-      // Is this the block we wanted?
-      if (base[i] == requested_addr) {
-        size[i] = bytes;
-        break;
-      }
-
-      // check that the gap value is right
-      if (had_top_overlap && !have_adjusted_gap) {
-        size_t actual_gap = base[i-1] - base[i] - bytes;
-        if (gap != actual_gap) {
-          // adjust the gap value and retry the last 2 allocations
-          assert(i > 0, "gap adjustment code problem");
-          have_adjusted_gap = true;  // adjust the gap only once, just in case
-          gap = actual_gap;
-          log_info(os)("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);
-          unmap_memory(base[i], bytes);
-          unmap_memory(base[i-1], size[i-1]);
-          i-=2;
-          continue;
-        }
-      }
-
-      // Does this overlap the block we wanted? Give back the overlapped
-      // parts and try again.
-      //
-      // There is still a bug in this code: if top_overlap == bytes,
-      // the overlap is offset from requested region by the value of gap.
-      // In this case giving back the overlapped part will not work,
-      // because we'll give back the entire block at base[i] and
-      // therefore the subsequent allocation will not generate a new gap.
-      // This could be fixed with a new algorithm that used larger
-      // or variable size chunks to find the requested region -
-      // but such a change would introduce additional complications.
-      // It's rare enough that the planets align for this bug,
-      // so we'll just wait for a fix for 6204603/5003415 which
-      // will provide a mmap flag to allow us to avoid this business.
-
-      size_t top_overlap = requested_addr + (bytes + gap) - base[i];
-      if (top_overlap >= 0 && top_overlap < bytes) {
-        had_top_overlap = true;
-        unmap_memory(base[i], top_overlap);
-        base[i] += top_overlap;
-        size[i] = bytes - top_overlap;
-      } else {
-        size_t bottom_overlap = base[i] + bytes - requested_addr;
-        if (bottom_overlap >= 0 && bottom_overlap < bytes) {
-          if (bottom_overlap == 0) {
-            log_info(os)("attempt_reserve_memory_at: possible alignment bug");
-          }
-          unmap_memory(requested_addr, bottom_overlap);
-          size[i] = bytes - bottom_overlap;
-        } else {
-          size[i] = bytes;
-        }
-      }
-    }
-  }
-
-  // Give back the unused reserved pieces.
-
-  for (int j = 0; j < i; ++j) {
-    if (base[j] != NULL) {
-      unmap_memory(base[j], size[j]);
-    }
-  }
-
-  return (i < max_tries) ? requested_addr : NULL;
+  return NULL;
 }
 
 bool os::pd_release_memory(char* addr, size_t bytes) {
--- a/src/hotspot/share/adlc/formssel.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/adlc/formssel.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -757,7 +757,6 @@
   return NO_MEMORY_OPERAND;
 }
 
-
 // This instruction captures the machine-independent bottom_type
 // Expected use is for pointer vs oop determination for LoadP
 bool InstructForm::captures_bottom_type(FormDict &globals) const {
@@ -775,8 +774,9 @@
        !strcmp(_matrule->_rChild->_opType,"GetAndSetP")   ||
        !strcmp(_matrule->_rChild->_opType,"GetAndSetN")   ||
 #if INCLUDE_ZGC
+       !strcmp(_matrule->_rChild->_opType,"ZGetAndSetP") ||
+       !strcmp(_matrule->_rChild->_opType,"ZCompareAndExchangeP") ||
        !strcmp(_matrule->_rChild->_opType,"LoadBarrierSlowReg") ||
-       !strcmp(_matrule->_rChild->_opType,"LoadBarrierWeakSlowReg") ||
 #endif
 #if INCLUDE_SHENANDOAHGC
        !strcmp(_matrule->_rChild->_opType,"ShenandoahCompareAndExchangeP") ||
@@ -3506,12 +3506,16 @@
     "CompareAndSwapB", "CompareAndSwapS", "CompareAndSwapI", "CompareAndSwapL", "CompareAndSwapP", "CompareAndSwapN",
     "WeakCompareAndSwapB", "WeakCompareAndSwapS", "WeakCompareAndSwapI", "WeakCompareAndSwapL", "WeakCompareAndSwapP", "WeakCompareAndSwapN",
     "CompareAndExchangeB", "CompareAndExchangeS", "CompareAndExchangeI", "CompareAndExchangeL", "CompareAndExchangeP", "CompareAndExchangeN",
+#if INCLUDE_SHENANDOAHGC
     "ShenandoahCompareAndSwapN", "ShenandoahCompareAndSwapP", "ShenandoahWeakCompareAndSwapP", "ShenandoahWeakCompareAndSwapN", "ShenandoahCompareAndExchangeP", "ShenandoahCompareAndExchangeN",
+#endif
     "StoreCM",
-    "ClearArray",
     "GetAndSetB", "GetAndSetS", "GetAndAddI", "GetAndSetI", "GetAndSetP",
     "GetAndAddB", "GetAndAddS", "GetAndAddL", "GetAndSetL", "GetAndSetN",
-    "LoadBarrierSlowReg", "LoadBarrierWeakSlowReg"
+#if INCLUDE_ZGC
+    "LoadBarrierSlowReg", "ZGetAndSetP", "ZCompareAndSwapP", "ZCompareAndExchangeP", "ZWeakCompareAndSwapP",
+#endif
+    "ClearArray"
   };
   int cnt = sizeof(needs_ideal_memory_list)/sizeof(char*);
   if( strcmp(_opType,"PrefetchAllocation")==0 )
--- a/src/hotspot/share/aot/aotCompiledMethod.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/aot/aotCompiledMethod.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -51,6 +51,7 @@
   int _scopes_begin;
   int _reloc_begin;
   int _exception_table_begin;
+  int _nul_chk_table_begin;
   int _oopmap_begin;
   address at_offset(size_t offset) const { return ((address) this) + offset; }
 public:
@@ -63,9 +64,9 @@
   relocInfo* relocation_begin() const { return (relocInfo*) at_offset(_reloc_begin); }
   relocInfo* relocation_end() const { return (relocInfo*) at_offset(_exception_table_begin); }
   address handler_table_begin   () const { return at_offset(_exception_table_begin); }
-  address handler_table_end() const { return at_offset(_oopmap_begin); }
+  address handler_table_end() const { return at_offset(_nul_chk_table_begin); }
 
-  address nul_chk_table_begin() const { return at_offset(_oopmap_begin); }
+  address nul_chk_table_begin() const { return at_offset(_nul_chk_table_begin); }
   address nul_chk_table_end() const { return at_offset(_oopmap_begin); }
 
   ImmutableOopMapSet* oopmap_set() const { return (ImmutableOopMapSet*) at_offset(_oopmap_begin); }
--- a/src/hotspot/share/asm/codeBuffer.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/asm/codeBuffer.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -413,6 +413,7 @@
                        || PrintMethodHandleStubs
                        || PrintInterpreter
                        || PrintSignatureHandlers
+                       || UnlockDiagnosticVMOptions
                         );
   }
 
--- a/src/hotspot/share/classfile/classFileParser.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/classfile/classFileParser.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -4754,60 +4754,62 @@
 
 // A legal major_version.minor_version must be one of the following:
 //
-//   Major_version = 45, any minor_version.
-//   Major_version >= 46 and major_version <= current_major_version and minor_version = 0.
-//   Major_version = current_major_version and minor_version = 65535 and --enable-preview is present.
+//  Major_version >= 45 and major_version < 56, any minor_version.
+//  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
+//  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
 //
 static void verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
+  ResourceMark rm(THREAD);
   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
-  if (major != JAVA_MIN_SUPPORTED_VERSION) { // All 45.* are ok including 45.65535
-    if (minor == JAVA_PREVIEW_MINOR_VERSION) {
-      if (major != max_version) {
-        ResourceMark rm(THREAD);
-        Exceptions::fthrow(
-          THREAD_AND_LOCATION,
-          vmSymbols::java_lang_UnsupportedClassVersionError(),
-          "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
-          "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
-          class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
-        return;
-      }
-
-      if (!Arguments::enable_preview()) {
-        ResourceMark rm(THREAD);
-        Exceptions::fthrow(
-          THREAD_AND_LOCATION,
-          vmSymbols::java_lang_UnsupportedClassVersionError(),
-          "Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
-          class_name->as_C_string(), major, minor);
-        return;
-      }
-
-    } else { // minor != JAVA_PREVIEW_MINOR_VERSION
-      if (major > max_version) {
-        ResourceMark rm(THREAD);
-        Exceptions::fthrow(
-          THREAD_AND_LOCATION,
-          vmSymbols::java_lang_UnsupportedClassVersionError(),
-          "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
-          "this version of the Java Runtime only recognizes class file versions up to %u.0",
-          class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
-      } else if (major < JAVA_MIN_SUPPORTED_VERSION) {
-        ResourceMark rm(THREAD);
-        Exceptions::fthrow(
-          THREAD_AND_LOCATION,
-          vmSymbols::java_lang_UnsupportedClassVersionError(),
-          "%s (class file version %u.%u) was compiled with an invalid major version",
-          class_name->as_C_string(), major, minor);
-      } else if (minor != 0) {
-        ResourceMark rm(THREAD);
-        Exceptions::fthrow(
-          THREAD_AND_LOCATION,
-          vmSymbols::java_lang_UnsupportedClassVersionError(),
-          "%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
-          class_name->as_C_string(), major, minor);
-      }
+  if (major < JAVA_MIN_SUPPORTED_VERSION) {
+    Exceptions::fthrow(
+      THREAD_AND_LOCATION,
+      vmSymbols::java_lang_UnsupportedClassVersionError(),
+      "%s (class file version %u.%u) was compiled with an invalid major version",
+      class_name->as_C_string(), major, minor);
+    return;
+  }
+
+  if (major > max_version) {
+    Exceptions::fthrow(
+      THREAD_AND_LOCATION,
+      vmSymbols::java_lang_UnsupportedClassVersionError(),
+      "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
+      "this version of the Java Runtime only recognizes class file versions up to %u.0",
+      class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
+    return;
+  }
+
+  if (major < JAVA_12_VERSION || minor == 0) {
+    return;
+  }
+
+  if (minor == JAVA_PREVIEW_MINOR_VERSION) {
+    if (major != max_version) {
+      Exceptions::fthrow(
+        THREAD_AND_LOCATION,
+        vmSymbols::java_lang_UnsupportedClassVersionError(),
+        "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
+        "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
+        class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
+      return;
     }
+
+    if (!Arguments::enable_preview()) {
+      Exceptions::fthrow(
+        THREAD_AND_LOCATION,
+        vmSymbols::java_lang_UnsupportedClassVersionError(),
+        "Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
+        class_name->as_C_string(), major, minor);
+      return;
+    }
+
+  } else { // minor != JAVA_PREVIEW_MINOR_VERSION
+    Exceptions::fthrow(
+        THREAD_AND_LOCATION,
+        vmSymbols::java_lang_UnsupportedClassVersionError(),
+        "%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
+        class_name->as_C_string(), major, minor);
   }
 }
 
@@ -5641,11 +5643,11 @@
     }
 
     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
-        ik->major_version() != JAVA_MIN_SUPPORTED_VERSION &&
+        ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
         log_is_enabled(Info, class, preview)) {
       ResourceMark rm;
       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
-                               ik->external_name(), ik->major_version());
+                               ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
     }
 
     if (log_is_enabled(Debug, class, resolve))  {
--- a/src/hotspot/share/classfile/stringTable.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/classfile/stringTable.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -58,8 +58,8 @@
 const double PREF_AVG_LIST_LEN = 2.0;
 // 2^24 is max size
 const size_t END_SIZE = 24;
-// If a chain gets to 32 something might be wrong
-const size_t REHASH_LEN = 32;
+// If a chain gets to 100 something might be wrong
+const size_t REHASH_LEN = 100;
 // If we have as many dead items as 50% of the number of bucket
 const double CLEAN_DEAD_HIGH_WATER_MARK = 0.5;
 
@@ -496,8 +496,9 @@
     return false;
   }
 
-  // We use max size
-  StringTableHash* new_table = new StringTableHash(END_SIZE, END_SIZE, REHASH_LEN);
+  // We use current size, not max size.
+  size_t new_size = _local_table->get_size_log2(Thread::current());
+  StringTableHash* new_table = new StringTableHash(new_size, END_SIZE, REHASH_LEN);
   // Use alt hash from now on
   _alt_hash = true;
   if (!_local_table->try_move_nodes_to(Thread::current(), new_table)) {
--- a/src/hotspot/share/classfile/symbolTable.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/classfile/symbolTable.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -267,7 +267,7 @@
   // all symbols from the dynamic table
   SymbolsDo sd(cl);
   if (!_local_table->try_scan(Thread::current(), sd)) {
-    log_info(stringtable)("symbols_do unavailable at this moment");
+    log_info(symboltable)("symbols_do unavailable at this moment");
   }
 }
 
@@ -557,7 +557,7 @@
   Thread* thr = Thread::current();
   VerifySymbols vs;
   if (!_local_table->try_scan(thr, vs)) {
-    log_info(stringtable)("verify unavailable at this moment");
+    log_info(symboltable)("verify unavailable at this moment");
   }
 }
 
@@ -763,8 +763,9 @@
     return false;
   }
 
-  // We use max size
-  SymbolTableHash* new_table = new SymbolTableHash(END_SIZE, END_SIZE, REHASH_LEN);
+  // We use current size
+  size_t new_size = _local_table->get_size_log2(Thread::current());
+  SymbolTableHash* new_table = new SymbolTableHash(new_size, END_SIZE, REHASH_LEN);
   // Use alt hash from now on
   _alt_hash = true;
   if (!_local_table->try_move_nodes_to(Thread::current(), new_table)) {
--- a/src/hotspot/share/code/codeCache.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/codeCache.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1284,7 +1284,7 @@
 
     if (heap->full_count() == 0) {
       if (PrintCodeHeapAnalytics) {
-        CompileBroker::print_heapinfo(tty, "all", "4096"); // details, may be a lot!
+        CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
       }
     }
   }
@@ -1571,7 +1571,7 @@
 
 //---<  BEGIN  >--- CodeHeap State Analytics.
 
-void CodeCache::aggregate(outputStream *out, const char* granularity) {
+void CodeCache::aggregate(outputStream *out, size_t granularity) {
   FOR_ALL_ALLOCABLE_HEAPS(heap) {
     CodeHeapState::aggregate(out, (*heap), granularity);
   }
--- a/src/hotspot/share/code/codeCache.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/codeCache.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -294,7 +294,7 @@
 
   // CodeHeap State Analytics.
   // interface methods for CodeHeap printing, called by CompileBroker
-  static void aggregate(outputStream *out, const char* granularity);
+  static void aggregate(outputStream *out, size_t granularity);
   static void discard(outputStream *out);
   static void print_usedSpace(outputStream *out);
   static void print_freeSpace(outputStream *out);
--- a/src/hotspot/share/code/codeHeapState.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/codeHeapState.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -530,7 +530,7 @@
   }
 }
 
-void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, const char* granularity_request) {
+void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, size_t granularity) {
   unsigned int nBlocks_free    = 0;
   unsigned int nBlocks_used    = 0;
   unsigned int nBlocks_zomb    = 0;
@@ -612,7 +612,8 @@
   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.
   //   This is necessary to prevent an unsigned short overflow while accumulating space information.
   //
-  size_t granularity = strtol(granularity_request, NULL, 0);
+  assert(granularity > 0, "granularity should be positive.");
+
   if (granularity > size) {
     granularity = size;
   }
--- a/src/hotspot/share/code/codeHeapState.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/codeHeapState.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -99,7 +99,7 @@
 
  public:
   static void discard(outputStream* out, CodeHeap* heap);
-  static void aggregate(outputStream* out, CodeHeap* heap, const char* granularity);
+  static void aggregate(outputStream* out, CodeHeap* heap, size_t granularity);
   static void print_usedSpace(outputStream* out, CodeHeap* heap);
   static void print_freeSpace(outputStream* out, CodeHeap* heap);
   static void print_count(outputStream* out, CodeHeap* heap);
--- a/src/hotspot/share/code/compiledMethod.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/compiledMethod.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "code/compiledIC.hpp"
 #include "code/compiledMethod.inline.hpp"
+#include "code/exceptionHandlerTable.hpp"
 #include "code/scopeDesc.hpp"
 #include "code/codeCache.hpp"
 #include "code/icBuffer.hpp"
@@ -37,8 +38,10 @@
 #include "oops/methodData.hpp"
 #include "oops/method.inline.hpp"
 #include "prims/methodHandles.hpp"
+#include "runtime/deoptimization.hpp"
 #include "runtime/handles.inline.hpp"
 #include "runtime/mutexLocker.hpp"
+#include "runtime/sharedRuntime.hpp"
 
 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, const CodeBlobLayout& layout,
                                int frame_complete_offset, int frame_size, ImmutableOopMapSet* oop_maps,
@@ -638,6 +641,46 @@
          os::is_readable_pointer(method->signature());
 }
 
+address CompiledMethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
+  // Exception happened outside inline-cache check code => we are inside
+  // an active nmethod => use cpc to determine a return address
+  int exception_offset = pc - code_begin();
+  int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
+#ifdef ASSERT
+  if (cont_offset == 0) {
+    Thread* thread = Thread::current();
+    ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
+    HandleMark hm(thread);
+    ResourceMark rm(thread);
+    CodeBlob* cb = CodeCache::find_blob(pc);
+    assert(cb != NULL && cb == this, "");
+    ttyLocker ttyl;
+    tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
+    print();
+    method()->print_codes();
+    print_code();
+    print_pcs();
+  }
+#endif
+  if (cont_offset == 0) {
+    // Let the normal error handling report the exception
+    return NULL;
+  }
+  if (cont_offset == exception_offset) {
+#if INCLUDE_JVMCI
+    Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
+    JavaThread *thread = JavaThread::current();
+    thread->set_jvmci_implicit_exception_pc(pc);
+    thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
+                                                                         Deoptimization::Action_reinterpret));
+    return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
+#else
+    ShouldNotReachHere();
+#endif
+  }
+  return code_begin() + cont_offset;
+}
+
 class HasEvolDependency : public MetadataClosure {
   bool _has_evol_dependency;
  public:
--- a/src/hotspot/share/code/compiledMethod.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/compiledMethod.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -350,7 +350,8 @@
   void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f);
 
   // implicit exceptions support
-  virtual address continuation_for_implicit_exception(address pc) { return NULL; }
+  address continuation_for_implicit_div0_exception(address pc) { return continuation_for_implicit_exception(pc, true); }
+  address continuation_for_implicit_null_exception(address pc) { return continuation_for_implicit_exception(pc, false); }
 
   static address get_deopt_original_pc(const frame* fr);
 
@@ -358,6 +359,8 @@
  private:
   bool cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all);
 
+  address continuation_for_implicit_exception(address pc, bool for_div0_check);
+
  public:
   // Serial version used by sweeper and whitebox test
   void cleanup_inline_caches(bool clean_all);
--- a/src/hotspot/share/code/dependencies.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/dependencies.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -373,8 +373,7 @@
     assert(ctxk->is_abstract(), "must be abstract");
   }
   static void check_unique_method(Klass* ctxk, Method* m) {
-    // Graal can register redundant dependencies
-    assert(UseJVMCICompiler || !m->can_be_statically_bound(InstanceKlass::cast(ctxk)), "redundant");
+    assert(!m->can_be_statically_bound(InstanceKlass::cast(ctxk)), "redundant");
   }
 
   void assert_common_1(DepType dept, DepValue x);
--- a/src/hotspot/share/code/exceptionHandlerTable.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/exceptionHandlerTable.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -176,7 +176,7 @@
   _len = l+1;
 };
 
-uint ImplicitExceptionTable::at( uint exec_off ) const {
+uint ImplicitExceptionTable::continuation_offset( uint exec_off ) const {
   uint l = len();
   for( uint i=0; i<l; i++ )
     if( *adr(i) == exec_off )
@@ -205,7 +205,7 @@
   }
 }
 
-ImplicitExceptionTable::ImplicitExceptionTable(const nmethod* nm) {
+ImplicitExceptionTable::ImplicitExceptionTable(const CompiledMethod* nm) {
   if (nm->nul_chk_table_size() == 0) {
     _len = 0;
     _data = NULL;
@@ -221,9 +221,13 @@
 }
 
 void ImplicitExceptionTable::copy_to( nmethod* nm ) {
-  assert(size_in_bytes() <= nm->nul_chk_table_size(), "size of space allocated in nmethod incorrect");
+  copy_bytes_to(nm->nul_chk_table_begin(), nm->nul_chk_table_size());
+}
+
+void ImplicitExceptionTable::copy_bytes_to(address addr, int size) {
+  assert(size_in_bytes() <= size, "size of space allocated in nmethod incorrect");
   if (len() != 0) {
-    implicit_null_entry* nmdata = (implicit_null_entry*)nm->nul_chk_table_begin();
+    implicit_null_entry* nmdata = (implicit_null_entry*)addr;
     // store the length in the first uint
     nmdata[0] = _len;
     nmdata++;
@@ -232,7 +236,7 @@
   } else {
     // zero length table takes zero bytes
     assert(size_in_bytes() == 0, "bad size");
-    assert(nm->nul_chk_table_size() == 0, "bad size");
+    assert(size == 0, "bad size");
   }
 }
 
--- a/src/hotspot/share/code/exceptionHandlerTable.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/exceptionHandlerTable.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -146,19 +146,36 @@
   implicit_null_entry *_data;
   implicit_null_entry *adr( uint idx ) const { return &_data[2*idx]; }
   ReallocMark          _nesting;  // assertion check for reallocations
+
 public:
   ImplicitExceptionTable( ) :  _size(0), _len(0), _data(0) { }
   // (run-time) construction from nmethod
-  ImplicitExceptionTable( const nmethod *nm );
+  ImplicitExceptionTable( const CompiledMethod *nm );
 
   void set_size( uint size );
   void append( uint exec_off, uint cont_off );
-  uint at( uint exec_off ) const;
+
+#if INCLUDE_JVMCI
+  void add_deoptimize(uint exec_off) {
+    // Use the same offset as a marker value for deoptimization
+    append(exec_off, exec_off);
+  }
+#endif
+
+  // Returns the offset to continue execution at.  If the returned
+  // value equals exec_off then the dispatch is expected to be a
+  // deoptimization instead.
+  uint continuation_offset( uint exec_off ) const;
 
   uint len() const { return _len; }
+
+  uint get_exec_offset(uint i) { assert(i < _len, "oob"); return *adr(i); }
+  uint get_cont_offset(uint i) { assert(i < _len, "oob"); return *(adr(i) + 1); }
+
   int size_in_bytes() const { return len() == 0 ? 0 : ((2 * len() + 1) * sizeof(implicit_null_entry)); }
 
   void copy_to(nmethod* nm);
+  void copy_bytes_to(address addr, int size);
   void print(address base) const;
   void verify(nmethod *nm) const;
 };
--- a/src/hotspot/share/code/nmethod.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/nmethod.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -923,6 +923,7 @@
   ttyLocker ttyl;  // keep the following output all in one block
   if (xtty != NULL) {
     xtty->begin_head("print_nmethod");
+    log_identity(xtty);
     xtty->stamp();
     xtty->end_head();
   }
@@ -2093,34 +2094,6 @@
 }
 
 
-address nmethod::continuation_for_implicit_exception(address pc) {
-  // Exception happened outside inline-cache check code => we are inside
-  // an active nmethod => use cpc to determine a return address
-  int exception_offset = pc - code_begin();
-  int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
-#ifdef ASSERT
-  if (cont_offset == 0) {
-    Thread* thread = Thread::current();
-    ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
-    HandleMark hm(thread);
-    ResourceMark rm(thread);
-    CodeBlob* cb = CodeCache::find_blob(pc);
-    assert(cb != NULL && cb == this, "");
-    ttyLocker ttyl;
-    tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
-    // Print all available nmethod info.
-    print_nmethod(true);
-    method()->print_codes();
-  }
-#endif
-  if (cont_offset == 0) {
-    // Let the normal error handling report the exception
-    return NULL;
-  }
-  return code_begin() + cont_offset;
-}
-
-
 void nmethod_init() {
   // make sure you didn't forget to adjust the filler fields
   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
@@ -2213,6 +2186,30 @@
     }
   }
 
+#ifdef ASSERT
+#if INCLUDE_JVMCI
+  {
+    // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
+    ImmutableOopMapSet* oms = oop_maps();
+    ImplicitExceptionTable implicit_table(this);
+    for (uint i = 0; i < implicit_table.len(); i++) {
+      int exec_offset = (int) implicit_table.get_exec_offset(i);
+      if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
+        assert(pc_desc_at(code_begin() + exec_offset) != NULL, "missing PcDesc");
+        bool found = false;
+        for (int i = 0, imax = oms->count(); i < imax; i++) {
+          if (oms->pair_at(i)->pc_offset() == exec_offset) {
+            found = true;
+            break;
+          }
+        }
+        assert(found, "missing oopmap");
+      }
+    }
+  }
+#endif
+#endif
+
   VerifyOopsClosure voc(this);
   oops_do(&voc);
   assert(voc.ok(), "embedded oops must be OK");
@@ -3012,16 +3009,32 @@
   if (str != NULL) return true;
 
   // implicit exceptions?
-  int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
+  int cont_offset = ImplicitExceptionTable(this).continuation_offset(begin - code_begin());
   if (cont_offset != 0) return true;
 
   return false;
 }
 
 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
-  // First, find an oopmap in (begin, end].
-  // We use the odd half-closed interval so that oop maps and scope descs
-  // which are tied to the byte after a call are printed with the call itself.
+  ImplicitExceptionTable implicit_table(this);
+  int pc_offset = begin - code_begin();
+  int cont_offset = implicit_table.continuation_offset(pc_offset);
+  bool oop_map_required = false;
+  if (cont_offset != 0) {
+    st->move_to(column, 6, 0);
+    if (pc_offset == cont_offset) {
+      st->print("; implicit exception: deoptimizes");
+      oop_map_required = true;
+    } else {
+      st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
+    }
+  }
+
+  // Find an oopmap in (begin, end].  We use the odd half-closed
+  // interval so that oop maps and scope descs which are tied to the
+  // byte after a call are printed with the call itself.  OopMaps
+  // associated with implicit exceptions are printed with the implicit
+  // instruction.
   address base = code_begin();
   ImmutableOopMapSet* oms = oop_maps();
   if (oms != NULL) {
@@ -3029,16 +3042,25 @@
       const ImmutableOopMapPair* pair = oms->pair_at(i);
       const ImmutableOopMap* om = pair->get_from(oms);
       address pc = base + pair->pc_offset();
-      if (pc > begin) {
-        if (pc <= end) {
+      if (pc >= begin) {
+#if INCLUDE_JVMCI
+        bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
+#else
+        bool is_implicit_deopt = false;
+#endif
+        if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
           st->move_to(column, 6, 0);
           st->print("; ");
           om->print_on(st);
+          oop_map_required = false;
         }
+      }
+      if (pc > end) {
         break;
       }
     }
   }
+  assert(!oop_map_required, "missed oopmap");
 
   // Print any debug info present at this pc.
   ScopeDesc* sd  = scope_desc_in(begin, end);
@@ -3128,12 +3150,6 @@
     st->move_to(column, 6, 0);
     st->print(";   {%s}", str);
   }
-  int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
-  if (cont_offset != 0) {
-    st->move_to(column, 6, 0);
-    st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
-  }
-
 }
 
 #endif
--- a/src/hotspot/share/code/nmethod.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/code/nmethod.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -424,9 +424,6 @@
   long  stack_traversal_mark()                    { return _stack_traversal_mark; }
   void  set_stack_traversal_mark(long l)          { _stack_traversal_mark = l; }
 
-  // implicit exceptions support
-  address continuation_for_implicit_exception(address pc);
-
   // On-stack replacement support
   int   osr_entry_bci() const                     { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
   address  osr_entry() const                      { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
--- a/src/hotspot/share/compiler/abstractDisassembler.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/abstractDisassembler.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -38,12 +38,12 @@
 bool AbstractDisassembler::_show_data_hex      = true;
 bool AbstractDisassembler::_show_data_int      = false;
 bool AbstractDisassembler::_show_data_float    = false;
-bool AbstractDisassembler::_align_instr        = false;
+bool AbstractDisassembler::_align_instr        = true;
 bool AbstractDisassembler::_show_pc            = true;
 bool AbstractDisassembler::_show_offset        = false;
-bool AbstractDisassembler::_show_structs       = false;
-bool AbstractDisassembler::_show_comment       = false;
-bool AbstractDisassembler::_show_block_comment = false;
+bool AbstractDisassembler::_show_structs       = true;
+bool AbstractDisassembler::_show_comment       = true;
+bool AbstractDisassembler::_show_block_comment = true;
 
 // set "true" to see what's in memory bit by bit
 // might prove cumbersome on platforms where instr_len is hard to find out
--- a/src/hotspot/share/compiler/compileBroker.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/compileBroker.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2640,7 +2640,7 @@
 //       That's a tradeoff which keeps together important blocks of output.
 //       At the same time, continuous tty_lock hold time is kept in check,
 //       preventing concurrently printing threads from stalling a long time.
-void CompileBroker::print_heapinfo(outputStream* out, const char* function, const char* granularity) {
+void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
   TimeStamp ts_total;
   TimeStamp ts_global;
   TimeStamp ts;
--- a/src/hotspot/share/compiler/compileBroker.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/compileBroker.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -417,7 +417,7 @@
 
   // CodeHeap State Analytics.
   static void print_info(outputStream *out);
-  static void print_heapinfo(outputStream *out, const char* function, const char* granularity );
+  static void print_heapinfo(outputStream *out, const char* function, size_t granularity);
 };
 
 #endif // SHARE_COMPILER_COMPILEBROKER_HPP
--- a/src/hotspot/share/compiler/compilerDirectives.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/compilerDirectives.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -67,7 +67,7 @@
     cflags(CloneMapDebug,           bool, false, CloneMapDebug) \
     cflags(IGVPrintLevel,           intx, PrintIdealGraphLevel, IGVPrintLevel) \
     cflags(MaxNodeLimit,            intx, MaxNodeLimit, MaxNodeLimit) \
-ZGC_ONLY(cflags(ZOptimizeLoadBarriers, bool, ZOptimizeLoadBarriers, ZOptimizeLoadBarriers))
+ZGC_ONLY(cflags(ZTraceLoadBarriers, bool, false, ZTraceLoadBarriers))
 #else
   #define compilerdirectives_c2_flags(cflags)
 #endif
--- a/src/hotspot/share/compiler/disassembler.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/disassembler.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -147,7 +147,10 @@
 
     if (AbstractDisassembler::show_comment()) {
       if ((_nm != NULL) && _nm->has_code_comment(pc0, pc)) {
-        _nm->print_code_comment_on(st, _post_decode_alignment, pc0, pc);
+        _nm->print_code_comment_on
+               (st,
+                _post_decode_alignment ? _post_decode_alignment : COMMENT_COLUMN,
+                pc0, pc);
         // this calls reloc_string_for which calls oop::print_value_on
       }
       print_hook_comments(pc0, _nm != NULL);
--- a/src/hotspot/share/compiler/oopMap.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/compiler/oopMap.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -379,12 +379,8 @@
           continue;
         }
 #ifdef ASSERT
-        // We can not verify the oop here if we are using ZGC, the oop
-        // will be bad in case we had a safepoint between a load and a
-        // load barrier.
-        if (!UseZGC &&
-            ((((uintptr_t)loc & (sizeof(*loc)-1)) != 0) ||
-             !Universe::heap()->is_in_or_null(*loc))) {
+        if ((((uintptr_t)loc & (sizeof(*loc)-1)) != 0) ||
+            !Universe::heap()->is_in_or_null(*loc)) {
           tty->print_cr("# Found non oop pointer.  Dumping state at failure");
           // try to dump out some helpful debugging information
           trace_codeblob_maps(fr, reg_map);
--- a/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/c2/barrierSetC2.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -259,6 +259,7 @@
     Optimization,
     Expansion
   };
+
   virtual bool array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, ArrayCopyPhase phase) const { return false; }
   virtual void clone_barrier_at_expansion(ArrayCopyNode* ac, Node* call, PhaseIterGVN& igvn) const;
 
@@ -273,7 +274,6 @@
   virtual void eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const { }
   virtual void enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {}
   virtual void eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {}
-  virtual void add_users_to_worklist(Unique_Node_List* worklist) const {}
 
   // Allow barrier sets to have shared state that is preserved across a compilation unit.
   // This could for example comprise macro nodes to be expanded during macro expansion.
@@ -286,17 +286,21 @@
   virtual bool is_gc_specific_loop_opts_pass(LoopOptsMode mode) const { return false; }
 
   virtual bool has_special_unique_user(const Node* node) const { return false; }
+  virtual bool needs_anti_dependence_check(const Node* node) const { return true; }
+
+  virtual void barrier_insertion_phase(Compile* C, PhaseIterGVN &igvn) const { }
 
   enum CompilePhase {
-    BeforeOptimize, /* post_parse = true */
-    BeforeExpand, /* post_parse = false */
+    BeforeOptimize,
+    BeforeLateInsertion,
+    BeforeMacroExpand,
     BeforeCodeGen
   };
-  virtual void verify_gc_barriers(Compile* compile, CompilePhase phase) const {}
 
   virtual bool flatten_gc_alias_type(const TypePtr*& adr_type) const { return false; }
 #ifdef ASSERT
   virtual bool verify_gc_alias_type(const TypePtr* adr_type, int offset) const { return false; }
+  virtual void verify_gc_barriers(Compile* compile, CompilePhase phase) const {}
 #endif
 
   virtual bool final_graph_reshaping(Compile* compile, Node* n, uint opcode) const { return false; }
@@ -310,8 +314,8 @@
   virtual bool matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const { return false; };
   virtual bool matcher_is_store_load_barrier(Node* x, uint xop) const { return false; }
 
-  virtual void igvn_add_users_to_worklist(PhaseIterGVN* igvn, Node* use) const {}
-  virtual void ccp_analyze(PhaseCCP* ccp, Unique_Node_List& worklist, Node* use) const {}
+  virtual void igvn_add_users_to_worklist(PhaseIterGVN* igvn, Node* use) const { }
+  virtual void ccp_analyze(PhaseCCP* ccp, Unique_Node_List& worklist, Node* use) const { }
 
   virtual Node* split_if_pre(PhaseIdealLoop* phase, Node* n) const { return NULL; }
   virtual bool build_loop_late_post(PhaseIdealLoop* phase, Node* n) const { return false; }
--- a/src/hotspot/share/gc/shared/gcArguments.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/gcArguments.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -33,8 +33,6 @@
 #include "utilities/defaultStream.hpp"
 #include "utilities/macros.hpp"
 
-size_t MinHeapSize = 0;
-
 size_t HeapAlignment = 0;
 size_t SpaceAlignment = 0;
 
@@ -122,7 +120,7 @@
   assert(MaxHeapSize >= MinHeapSize, "Ergonomics decided on incompatible minimum and maximum heap sizes");
   assert(InitialHeapSize >= MinHeapSize, "Ergonomics decided on incompatible initial and minimum heap sizes");
   assert(MaxHeapSize >= InitialHeapSize, "Ergonomics decided on incompatible initial and maximum heap sizes");
-  assert(MaxHeapSize % HeapAlignment == 0, "MinHeapSize alignment");
+  assert(MinHeapSize % HeapAlignment == 0, "MinHeapSize alignment");
   assert(InitialHeapSize % HeapAlignment == 0, "InitialHeapSize alignment");
   assert(MaxHeapSize % HeapAlignment == 0, "MaxHeapSize alignment");
 }
@@ -149,7 +147,7 @@
     if (FLAG_IS_CMDLINE(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
       vm_exit_during_initialization("Initial heap size set to a larger value than the maximum heap size");
     }
-    if (MinHeapSize != 0 && MaxHeapSize < MinHeapSize) {
+    if (FLAG_IS_CMDLINE(MinHeapSize) && MaxHeapSize < MinHeapSize) {
       vm_exit_during_initialization("Incompatible minimum and maximum heap sizes specified");
     }
   }
@@ -166,28 +164,28 @@
   }
 
   // User inputs from -Xmx and -Xms must be aligned
-  MinHeapSize = align_up(MinHeapSize, HeapAlignment);
-  size_t aligned_initial_heap_size = align_up(InitialHeapSize, HeapAlignment);
-  size_t aligned_max_heap_size = align_up(MaxHeapSize, HeapAlignment);
-
   // Write back to flags if the values changed
-  if (aligned_initial_heap_size != InitialHeapSize) {
-    FLAG_SET_ERGO(InitialHeapSize, aligned_initial_heap_size);
+  if (!is_aligned(MinHeapSize, HeapAlignment)) {
+    FLAG_SET_ERGO(MinHeapSize, align_up(MinHeapSize, HeapAlignment));
   }
-  if (aligned_max_heap_size != MaxHeapSize) {
-    FLAG_SET_ERGO(MaxHeapSize, aligned_max_heap_size);
+  if (!is_aligned(InitialHeapSize, HeapAlignment)) {
+    FLAG_SET_ERGO(InitialHeapSize, align_up(InitialHeapSize, HeapAlignment));
+  }
+  if (!is_aligned(MaxHeapSize, HeapAlignment)) {
+    FLAG_SET_ERGO(MaxHeapSize, align_up(MaxHeapSize, HeapAlignment));
   }
 
-  if (FLAG_IS_CMDLINE(InitialHeapSize) && MinHeapSize != 0 &&
+  if (FLAG_IS_CMDLINE(InitialHeapSize) && FLAG_IS_CMDLINE(MinHeapSize) &&
       InitialHeapSize < MinHeapSize) {
     vm_exit_during_initialization("Incompatible minimum and initial heap sizes specified");
   }
+
   if (!FLAG_IS_DEFAULT(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
     FLAG_SET_ERGO(MaxHeapSize, InitialHeapSize);
   } else if (!FLAG_IS_DEFAULT(MaxHeapSize) && InitialHeapSize > MaxHeapSize) {
     FLAG_SET_ERGO(InitialHeapSize, MaxHeapSize);
     if (InitialHeapSize < MinHeapSize) {
-      MinHeapSize = InitialHeapSize;
+      FLAG_SET_ERGO(MinHeapSize, InitialHeapSize);
     }
   }
 
--- a/src/hotspot/share/gc/shared/gcArguments.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/gcArguments.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -30,8 +30,6 @@
 
 class CollectedHeap;
 
-extern size_t MinHeapSize;
-
 extern size_t HeapAlignment;
 extern size_t SpaceAlignment;
 
--- a/src/hotspot/share/gc/shared/gc_globals.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/gc_globals.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -713,6 +713,10 @@
           "to move")                                                        \
                                                                             \
   /* gc parameters */                                                       \
+  product(size_t, MinHeapSize, 0,                                           \
+          "Minimum heap size (in bytes); zero means use ergonomics")        \
+          constraint(MinHeapSizeConstraintFunc,AfterErgo)                   \
+                                                                            \
   product(size_t, InitialHeapSize, 0,                                       \
           "Initial heap size (in bytes); zero means use ergonomics")        \
           constraint(InitialHeapSizeConstraintFunc,AfterErgo)               \
--- a/src/hotspot/share/gc/shared/genArguments.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/genArguments.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -90,7 +90,7 @@
   }
   // If needed, synchronize MinHeapSize size and InitialHeapSize
   if (MinHeapSize < smallest_heap_size) {
-    MinHeapSize = smallest_heap_size;
+    FLAG_SET_ERGO(MinHeapSize, smallest_heap_size);
     if (InitialHeapSize < MinHeapSize) {
       FLAG_SET_ERGO(InitialHeapSize, smallest_heap_size);
     }
--- a/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -319,6 +319,10 @@
   return MaxSizeForAlignment(name, value, heap_alignment, verbose);
 }
 
+JVMFlag::Error MinHeapSizeConstraintFunc(size_t value, bool verbose) {
+  return MaxSizeForHeapAlignment("MinHeapSize", value, verbose);
+}
+
 JVMFlag::Error InitialHeapSizeConstraintFunc(size_t value, bool verbose) {
   return MaxSizeForHeapAlignment("InitialHeapSize", value, verbose);
 }
--- a/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shared/jvmFlagConstraintsGC.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -59,6 +59,7 @@
 JVMFlag::Error MaxGCPauseMillisConstraintFunc(uintx value, bool verbose);
 JVMFlag::Error GCPauseIntervalMillisConstraintFunc(uintx value, bool verbose);
 JVMFlag::Error InitialBootClassLoaderMetaspaceSizeConstraintFunc(size_t value, bool verbose);
+JVMFlag::Error MinHeapSizeConstraintFunc(size_t value, bool verbose);
 JVMFlag::Error InitialHeapSizeConstraintFunc(size_t value, bool verbose);
 JVMFlag::Error MaxHeapSizeConstraintFunc(size_t value, bool verbose);
 JVMFlag::Error SoftMaxHeapSizeConstraintFunc(size_t value, bool verbose);
--- a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -912,8 +912,6 @@
   }
 }
 
-void ShenandoahBarrierSetC2::add_users_to_worklist(Unique_Node_List* worklist) const {}
-
 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
 }
@@ -928,7 +926,7 @@
 
 #ifdef ASSERT
 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
-  if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeExpand) {
+  if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
     ShenandoahBarrierC2Support::verify(Compile::current()->root());
   } else if (phase == BarrierSetC2::BeforeCodeGen) {
     // Verify G1 pre-barriers
--- a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -126,7 +126,6 @@
   virtual void eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const;
   virtual void enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const;
   virtual void eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const;
-  virtual void add_users_to_worklist(Unique_Node_List* worklist) const;
 
   // Allow barrier sets to have shared state that is preserved across a compilation unit.
   // This could for example comprise macro nodes to be expanded during macro expansion.
--- a/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, 2018, Red Hat, Inc. All rights reserved.
+ * Copyright (c) 2017, 2019, Red Hat, Inc. All rights reserved.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
@@ -122,7 +122,7 @@
   void possibly_parallel_blobs_do(CodeBlobClosure* f);
 };
 
-class ShenandoahCodeRoots : public CHeapObj<mtGC> {
+class ShenandoahCodeRoots : public AllStatic {
   friend class ShenandoahHeap;
   friend class ShenandoahCodeRootsIterator;
 
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -60,8 +60,7 @@
   _object_synchronizer_root(&ObjectSynchronizer::oops_do, ShenandoahPhaseTimings::ObjectSynchronizerRoots),
   _management_root(&Management::oops_do, ShenandoahPhaseTimings::ManagementRoots),
   _system_dictionary_root(&SystemDictionary::oops_do, ShenandoahPhaseTimings::SystemDictionaryRoots),
-  _jvmti_root(&JvmtiExport::oops_do, ShenandoahPhaseTimings::JVMTIRoots),
-  _jni_handle_root(&JNIHandles::oops_do, ShenandoahPhaseTimings::JNIRoots) {
+  _jvmti_root(&JvmtiExport::oops_do, ShenandoahPhaseTimings::JVMTIRoots) {
 }
 
 void ShenandoahSerialRoots::oops_do(OopClosure* cl, uint worker_id) {
@@ -70,7 +69,10 @@
   _management_root.oops_do(cl, worker_id);
   _system_dictionary_root.oops_do(cl, worker_id);
   _jvmti_root.oops_do(cl, worker_id);
-  _jni_handle_root.oops_do(cl, worker_id);
+}
+
+ShenandoahJNIHandleRoots::ShenandoahJNIHandleRoots() :
+  ShenandoahSerialRoot(&JNIHandles::oops_do, ShenandoahPhaseTimings::JNIRoots) {
 }
 
 ShenandoahThreadRoots::ShenandoahThreadRoots(bool is_par) : _is_par(is_par) {
@@ -160,6 +162,7 @@
   AlwaysTrueClosure always_true;
 
   _serial_roots.oops_do(oops, worker_id);
+  _jni_roots.oops_do(oops, worker_id);
 
   _thread_roots.oops_do(oops, NULL, worker_id);
   _cld_roots.clds_do(&clds, &clds, worker_id);
@@ -189,6 +192,7 @@
   AlwaysTrueClosure always_true;
 
   _serial_roots.oops_do(oops, worker_id);
+  _jni_roots.oops_do(oops, worker_id);
 
   _thread_roots.oops_do(oops, NULL, worker_id);
   _cld_roots.clds_do(&adjust_cld_closure, NULL, worker_id);
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -56,12 +56,16 @@
   ShenandoahSerialRoot  _management_root;
   ShenandoahSerialRoot  _system_dictionary_root;
   ShenandoahSerialRoot  _jvmti_root;
-  ShenandoahSerialRoot  _jni_handle_root;
 public:
   ShenandoahSerialRoots();
   void oops_do(OopClosure* cl, uint worker_id);
 };
 
+class ShenandoahJNIHandleRoots : public ShenandoahSerialRoot {
+public:
+  ShenandoahJNIHandleRoots();
+};
+
 class ShenandoahThreadRoots {
 private:
   const bool _is_par;
@@ -126,6 +130,7 @@
 class ShenandoahRootScanner : public ShenandoahRootProcessor {
 private:
   ShenandoahSerialRoots          _serial_roots;
+  ShenandoahJNIHandleRoots       _jni_roots;
   ShenandoahClassLoaderDataRoots _cld_roots;
   ShenandoahThreadRoots          _thread_roots;
   ShenandoahCodeCacheRoots<ITR>  _code_roots;
@@ -152,6 +157,7 @@
 class ShenandoahRootEvacuator : public ShenandoahRootProcessor {
 private:
   ShenandoahSerialRoots          _serial_roots;
+  ShenandoahJNIHandleRoots       _jni_roots;
   ShenandoahClassLoaderDataRoots _cld_roots;
   ShenandoahThreadRoots          _thread_roots;
   ShenandoahWeakRoots            _weak_roots;
@@ -168,6 +174,7 @@
 class ShenandoahRootUpdater : public ShenandoahRootProcessor {
 private:
   ShenandoahSerialRoots          _serial_roots;
+  ShenandoahJNIHandleRoots       _jni_roots;
   ShenandoahClassLoaderDataRoots _cld_roots;
   ShenandoahThreadRoots          _thread_roots;
   ShenandoahWeakRoots            _weak_roots;
@@ -186,6 +193,7 @@
 class ShenandoahRootAdjuster : public ShenandoahRootProcessor {
 private:
   ShenandoahSerialRoots          _serial_roots;
+  ShenandoahJNIHandleRoots       _jni_roots;
   ShenandoahClassLoaderDataRoots _cld_roots;
   ShenandoahThreadRoots          _thread_roots;
   ShenandoahWeakRoots            _weak_roots;
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.inline.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.inline.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -99,6 +99,7 @@
   ResourceMark rm;
 
   _serial_roots.oops_do(oops, worker_id);
+  _jni_roots.oops_do(oops, worker_id);
   _cld_roots.clds_do(clds, clds, worker_id);
   _thread_roots.threads_do(&tc_cl, worker_id);
 
@@ -118,6 +119,7 @@
   ResourceMark rm;
 
   _serial_roots.oops_do(oops, 0);
+  _jni_roots.oops_do(oops, 0);
   _cld_roots.clds_do(&clds, &clds, 0);
   _thread_roots.threads_do(&tc_cl, 0);
   _code_roots.code_blobs_do(&code, 0);
@@ -130,6 +132,7 @@
   ResourceMark rm;
 
   _serial_roots.oops_do(oops, worker_id);
+  _jni_roots.oops_do(oops, worker_id);
   _cld_roots.clds_do(clds, NULL, worker_id);
   _thread_roots.threads_do(&tc_cl, worker_id);
 }
@@ -141,6 +144,7 @@
   CLDToOopClosure* weak_clds = ShenandoahHeap::heap()->unload_classes() ? NULL : &clds;
 
   _serial_roots.oops_do(keep_alive, worker_id);
+  _jni_roots.oops_do(keep_alive, worker_id);
 
   _thread_roots.oops_do(keep_alive, NULL, worker_id);
   _cld_roots.clds_do(&clds, weak_clds, worker_id);
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootVerifier.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootVerifier.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -69,15 +69,18 @@
 
   if (verify(SerialRoots)) {
     shenandoah_assert_safepoint();
-
     Universe::oops_do(oops);
     Management::oops_do(oops);
     JvmtiExport::oops_do(oops);
-    JNIHandles::oops_do(oops);
     ObjectSynchronizer::oops_do(oops);
     SystemDictionary::oops_do(oops);
   }
 
+  if (verify(JNIHandleRoots)) {
+    shenandoah_assert_safepoint();
+    JNIHandles::oops_do(oops);
+  }
+
   if (verify(WeakRoots)) {
     shenandoah_assert_safepoint();
     AlwaysTrueClosure always_true;
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootVerifier.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootVerifier.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -36,7 +36,8 @@
     CLDGRoots           = 1 << 3,
     WeakRoots           = 1 << 4,
     StringDedupRoots    = 1 << 5,
-    AllRoots            = (SerialRoots | ThreadRoots | CodeRoots | CLDGRoots | WeakRoots | StringDedupRoots)
+    JNIHandleRoots      = 1 << 6,
+    AllRoots            = (SerialRoots | ThreadRoots | CodeRoots | CLDGRoots | WeakRoots | StringDedupRoots | JNIHandleRoots)
   };
 
 private:
--- a/src/hotspot/share/gc/z/c2/zBarrierSetC2.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/c2/zBarrierSetC2.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -22,15 +22,22 @@
  */
 
 #include "precompiled.hpp"
+#include "opto/castnode.hpp"
 #include "opto/compile.hpp"
-#include "opto/castnode.hpp"
 #include "opto/escape.hpp"
 #include "opto/graphKit.hpp"
-#include "opto/idealKit.hpp"
 #include "opto/loopnode.hpp"
+#include "opto/machnode.hpp"
 #include "opto/macro.hpp"
+#include "opto/memnode.hpp"
+#include "opto/movenode.hpp"
 #include "opto/node.hpp"
+#include "opto/phase.hpp"
+#include "opto/phaseX.hpp"
+#include "opto/rootnode.hpp"
 #include "opto/type.hpp"
+#include "utilities/copy.hpp"
+#include "utilities/growableArray.hpp"
 #include "utilities/macros.hpp"
 #include "gc/z/zBarrierSet.hpp"
 #include "gc/z/c2/zBarrierSetC2.hpp"
@@ -84,7 +91,7 @@
   if (node->is_Phi()) {
     PhiNode* phi = node->as_Phi();
     Node* n = phi->in(1);
-    if (n != NULL && (n->is_LoadBarrierSlowReg() ||  n->is_LoadBarrierWeakSlowReg())) {
+    if (n != NULL && n->is_LoadBarrierSlowReg()) {
       return true;
     }
   }
@@ -121,50 +128,19 @@
   }
 }
 
-void ZBarrierSetC2::find_dominating_barriers(PhaseIterGVN& igvn) {
-  // Look for dominating barriers on the same address only once all
-  // other loop opts are over. Loop opts may cause a safepoint to be
-  // inserted between a barrier and its dominating barrier.
-  Compile* C = Compile::current();
-  ZBarrierSetC2* bs = (ZBarrierSetC2*)BarrierSet::barrier_set()->barrier_set_c2();
-  ZBarrierSetC2State* s = bs->state();
-  if (s->load_barrier_count() >= 2) {
-    Compile::TracePhase tp("idealLoop", &C->timers[Phase::_t_idealLoop]);
-    PhaseIdealLoop::optimize(igvn, LoopOptsLastRound);
-    if (C->major_progress()) C->print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
-  }
-}
-
-void ZBarrierSetC2::add_users_to_worklist(Unique_Node_List* worklist) const {
-  // Permanent temporary workaround
-  // Loadbarriers may have non-obvious dead uses keeping them alive during parsing. The use is
-  // removed by RemoveUseless (after parsing, before optimize) but the barriers won't be added to
-  // the worklist. Unless we add them explicitly they are not guaranteed to end up there.
-  ZBarrierSetC2State* s = state();
+static bool load_require_barrier(LoadNode* load)      { return ((load->barrier_data() & RequireBarrier) != 0); }
+static bool load_has_weak_barrier(LoadNode* load)     { return ((load->barrier_data() & WeakBarrier) != 0); }
+static bool load_has_expanded_barrier(LoadNode* load) { return ((load->barrier_data() & ExpandedBarrier) != 0); }
+static void load_set_expanded_barrier(LoadNode* load) { return load->set_barrier_data(ExpandedBarrier); }
 
-  for (int i = 0; i < s->load_barrier_count(); i++) {
-    LoadBarrierNode* n = s->load_barrier_node(i);
-    worklist->push(n);
+static void load_set_barrier(LoadNode* load, bool weak)    {
+  if (weak) {
+    load->set_barrier_data(WeakBarrier);
+  } else {
+    load->set_barrier_data(RequireBarrier);
   }
 }
 
-const TypeFunc* ZBarrierSetC2::load_barrier_Type() const {
-  const Type** fields;
-
-  // Create input types (domain)
-  fields = TypeTuple::fields(2);
-  fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;
-  fields[TypeFunc::Parms+1] = TypeOopPtr::BOTTOM;
-  const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
-
-  // Create result type (range)
-  fields = TypeTuple::fields(1);
-  fields[TypeFunc::Parms+0] = TypeInstPtr::BOTTOM;
-  const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
-
-  return TypeFunc::make(domain, range);
-}
-
 // == LoadBarrierNode ==
 
 LoadBarrierNode::LoadBarrierNode(Compile* C,
@@ -172,13 +148,9 @@
                                  Node* mem,
                                  Node* val,
                                  Node* adr,
-                                 bool weak,
-                                 bool writeback,
-                                 bool oop_reload_allowed) :
+                                 bool weak) :
     MultiNode(Number_of_Inputs),
-    _weak(weak),
-    _writeback(writeback),
-    _oop_reload_allowed(oop_reload_allowed) {
+    _weak(weak) {
   init_req(Control, c);
   init_req(Memory, mem);
   init_req(Oop, val);
@@ -217,8 +189,8 @@
   const Type** floadbarrier = (const Type **)(phase->C->type_arena()->Amalloc_4((Number_of_Outputs)*sizeof(Type*)));
   const Type* val_t = phase->type(in(Oop));
   floadbarrier[Control] = Type::CONTROL;
-  floadbarrier[Memory] = Type::MEMORY;
-  floadbarrier[Oop] = val_t;
+  floadbarrier[Memory]  = Type::MEMORY;
+  floadbarrier[Oop]     = val_t;
   return TypeTuple::make(Number_of_Outputs, floadbarrier);
 }
 
@@ -238,6 +210,11 @@
 }
 
 LoadBarrierNode* LoadBarrierNode::has_dominating_barrier(PhaseIdealLoop* phase, bool linear_only, bool look_for_similar) {
+  if (is_weak()) {
+    // Weak barriers can't be eliminated
+    return NULL;
+  }
+
   Node* val = in(LoadBarrierNode::Oop);
   if (in(Similar)->is_Proj() && in(Similar)->in(0)->is_LoadBarrier()) {
     LoadBarrierNode* lb = in(Similar)->in(0)->as_LoadBarrier();
@@ -266,7 +243,7 @@
     }
   }
 
-  if (ZVerifyLoadBarriers || can_be_eliminated()) {
+  if (can_be_eliminated()) {
     return NULL;
   }
 
@@ -316,7 +293,7 @@
         }
         if (ok) {
           assert(dom_found, "");
-          return u->as_LoadBarrier();;
+          return u->as_LoadBarrier();
         }
         break;
       }
@@ -328,6 +305,7 @@
 
 void LoadBarrierNode::push_dominated_barriers(PhaseIterGVN* igvn) const {
   // Change to that barrier may affect a dominated barrier so re-push those
+  assert(!is_weak(), "sanity");
   Node* val = in(LoadBarrierNode::Oop);
 
   for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
@@ -355,13 +333,9 @@
 }
 
 Node *LoadBarrierNode::Identity(PhaseGVN *phase) {
-  if (!phase->C->directive()->ZOptimizeLoadBarriersOption) {
-    return this;
-  }
-
-  bool redundant_addr = false;
   LoadBarrierNode* dominating_barrier = has_dominating_barrier(NULL, true, false);
   if (dominating_barrier != NULL) {
+    assert(!is_weak(), "Weak barriers cant be eliminated");
     assert(dominating_barrier->in(Oop) == in(Oop), "");
     return dominating_barrier;
   }
@@ -374,33 +348,33 @@
     return this;
   }
 
-  Node* val = in(Oop);
-  Node* mem = in(Memory);
-  Node* ctrl = in(Control);
-  Node* adr = in(Address);
+  Node *val = in(Oop);
+  Node *mem = in(Memory);
+  Node *ctrl = in(Control);
+
   assert(val->Opcode() != Op_LoadN, "");
+  assert(val->Opcode() != Op_DecodeN, "");
 
   if (mem->is_MergeMem()) {
-    Node* new_mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
+    Node *new_mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
     set_req(Memory, new_mem);
     if (mem->outcnt() == 0 && can_reshape) {
       phase->is_IterGVN()->_worklist.push(mem);
     }
-
     return this;
   }
 
-  bool optimizeLoadBarriers = phase->C->directive()->ZOptimizeLoadBarriersOption;
-  LoadBarrierNode* dominating_barrier = optimizeLoadBarriers ? has_dominating_barrier(NULL, !can_reshape, !phase->C->major_progress()) : NULL;
-  if (dominating_barrier != NULL && dominating_barrier->in(Oop) != in(Oop)) {
-    assert(in(Address) == dominating_barrier->in(Address), "");
-    set_req(Similar, dominating_barrier->proj_out(Oop));
-    return this;
+  LoadBarrierNode *dominating_barrier = NULL;
+  if (!is_weak()) {
+    dominating_barrier = has_dominating_barrier(NULL, !can_reshape, !phase->C->major_progress());
+    if (dominating_barrier != NULL && dominating_barrier->in(Oop) != in(Oop)) {
+      assert(in(Address) == dominating_barrier->in(Address), "");
+      set_req(Similar, dominating_barrier->proj_out(Oop));
+      return this;
+    }
   }
 
-  bool eliminate = (optimizeLoadBarriers && !(val->is_Phi() || val->Opcode() == Op_LoadP || val->Opcode() == Op_GetAndSetP || val->is_DecodeN())) ||
-                   (can_reshape && (dominating_barrier != NULL || !has_true_uses()));
-
+  bool eliminate = can_reshape && (dominating_barrier != NULL || !has_true_uses());
   if (eliminate) {
     if (can_reshape) {
       PhaseIterGVN* igvn = phase->is_IterGVN();
@@ -415,13 +389,13 @@
       fix_similar_in_uses(igvn);
       if (out_res != NULL) {
         if (dominating_barrier != NULL) {
+          assert(!is_weak(), "Sanity");
           igvn->replace_node(out_res, dominating_barrier->proj_out(Oop));
         } else {
           igvn->replace_node(out_res, val);
         }
       }
     }
-
     return new ConINode(TypeInt::ZERO);
   }
 
@@ -432,7 +406,7 @@
     return this;
   }
 
-  if (can_reshape) {
+  if (can_reshape && !is_weak()) {
     // If this barrier is linked through the Similar edge by a
     // dominated barrier and both barriers have the same Oop field,
     // the dominated barrier can go away, so push it for reprocessing.
@@ -446,10 +420,10 @@
       Node* u = out_res->fast_out(i);
       if (u->is_LoadBarrier() && u->in(Similar) == out_res &&
           (u->in(Oop) == val || !u->in(Similar)->is_top())) {
+        assert(!u->as_LoadBarrier()->is_weak(), "Sanity");
         igvn->_worklist.push(u);
       }
     }
-
     push_dominated_barriers(igvn);
   }
 
@@ -479,211 +453,17 @@
 
 bool LoadBarrierNode::has_true_uses() const {
   Node* out_res = proj_out_or_null(Oop);
-  if (out_res == NULL) {
-    return false;
-  }
-
-  for (DUIterator_Fast imax, i = out_res->fast_outs(imax); i < imax; i++) {
-    Node* u = out_res->fast_out(i);
-    if (!u->is_LoadBarrier() || u->in(Similar) != out_res) {
-      return true;
+  if (out_res != NULL) {
+    for (DUIterator_Fast imax, i = out_res->fast_outs(imax); i < imax; i++) {
+      Node *u = out_res->fast_out(i);
+      if (!u->is_LoadBarrier() || u->in(Similar) != out_res) {
+        return true;
+      }
     }
   }
-
   return false;
 }
 
-// == Accesses ==
-
-Node* ZBarrierSetC2::make_cas_loadbarrier(C2AtomicParseAccess& access) const {
-  assert(!UseCompressedOops, "Not allowed");
-  CompareAndSwapNode* cas = (CompareAndSwapNode*)access.raw_access();
-  PhaseGVN& gvn = access.gvn();
-  Compile* C = Compile::current();
-  GraphKit* kit = access.kit();
-
-  Node* in_ctrl     = cas->in(MemNode::Control);
-  Node* in_mem      = cas->in(MemNode::Memory);
-  Node* in_adr      = cas->in(MemNode::Address);
-  Node* in_val      = cas->in(MemNode::ValueIn);
-  Node* in_expected = cas->in(LoadStoreConditionalNode::ExpectedIn);
-
-  float likely                   = PROB_LIKELY(0.999);
-
-  const TypePtr *adr_type        = gvn.type(in_adr)->isa_ptr();
-  Compile::AliasType* alias_type = C->alias_type(adr_type);
-  int alias_idx                  = C->get_alias_index(adr_type);
-
-  // Outer check - true: continue, false: load and check
-  Node* region   = new RegionNode(3);
-  Node* phi      = new PhiNode(region, TypeInt::BOOL);
-  Node* phi_mem  = new PhiNode(region, Type::MEMORY, adr_type);
-
-  // Inner check - is the healed ref equal to the expected
-  Node* region2  = new RegionNode(3);
-  Node* phi2     = new PhiNode(region2, TypeInt::BOOL);
-  Node* phi_mem2 = new PhiNode(region2, Type::MEMORY, adr_type);
-
-  // CAS node returns 0 or 1
-  Node* cmp     = gvn.transform(new CmpINode(cas, kit->intcon(0)));
-  Node* bol     = gvn.transform(new BoolNode(cmp, BoolTest::ne))->as_Bool();
-  IfNode* iff   = gvn.transform(new IfNode(in_ctrl, bol, likely, COUNT_UNKNOWN))->as_If();
-  Node* then    = gvn.transform(new IfTrueNode(iff));
-  Node* elsen   = gvn.transform(new IfFalseNode(iff));
-
-  Node* scmemproj1   = gvn.transform(new SCMemProjNode(cas));
-
-  kit->set_memory(scmemproj1, alias_idx);
-  phi_mem->init_req(1, scmemproj1);
-  phi_mem2->init_req(2, scmemproj1);
-
-  // CAS fail - reload and heal oop
-  Node* reload      = kit->make_load(elsen, in_adr, TypeOopPtr::BOTTOM, T_OBJECT, MemNode::unordered);
-  Node* barrier     = gvn.transform(new LoadBarrierNode(C, elsen, scmemproj1, reload, in_adr, false, true, false));
-  Node* barrierctrl = gvn.transform(new ProjNode(barrier, LoadBarrierNode::Control));
-  Node* barrierdata = gvn.transform(new ProjNode(barrier, LoadBarrierNode::Oop));
-
-  // Check load
-  Node* tmpX    = gvn.transform(new CastP2XNode(NULL, barrierdata));
-  Node* in_expX = gvn.transform(new CastP2XNode(NULL, in_expected));
-  Node* cmp2    = gvn.transform(new CmpXNode(tmpX, in_expX));
-  Node *bol2    = gvn.transform(new BoolNode(cmp2, BoolTest::ne))->as_Bool();
-  IfNode* iff2  = gvn.transform(new IfNode(barrierctrl, bol2, likely, COUNT_UNKNOWN))->as_If();
-  Node* then2   = gvn.transform(new IfTrueNode(iff2));
-  Node* elsen2  = gvn.transform(new IfFalseNode(iff2));
-
-  // redo CAS
-  Node* cas2       = gvn.transform(new CompareAndSwapPNode(elsen2, kit->memory(alias_idx), in_adr, in_val, in_expected, cas->order()));
-  Node* scmemproj2 = gvn.transform(new SCMemProjNode(cas2));
-  kit->set_control(elsen2);
-  kit->set_memory(scmemproj2, alias_idx);
-
-  // Merge inner flow - check if healed oop was equal too expected.
-  region2->set_req(1, kit->control());
-  region2->set_req(2, then2);
-  phi2->set_req(1, cas2);
-  phi2->set_req(2, kit->intcon(0));
-  phi_mem2->init_req(1, scmemproj2);
-  kit->set_memory(phi_mem2, alias_idx);
-
-  // Merge outer flow - then check if first CAS succeeded
-  region->set_req(1, then);
-  region->set_req(2, region2);
-  phi->set_req(1, kit->intcon(1));
-  phi->set_req(2, phi2);
-  phi_mem->init_req(2, phi_mem2);
-  kit->set_memory(phi_mem, alias_idx);
-
-  gvn.transform(region2);
-  gvn.transform(phi2);
-  gvn.transform(phi_mem2);
-  gvn.transform(region);
-  gvn.transform(phi);
-  gvn.transform(phi_mem);
-
-  kit->set_control(region);
-  kit->insert_mem_bar(Op_MemBarCPUOrder);
-
-  return phi;
-}
-
-Node* ZBarrierSetC2::make_cmpx_loadbarrier(C2AtomicParseAccess& access) const {
-  CompareAndExchangePNode* cmpx = (CompareAndExchangePNode*)access.raw_access();
-  GraphKit* kit = access.kit();
-  PhaseGVN& gvn = kit->gvn();
-  Compile* C = Compile::current();
-
-  Node* in_ctrl     = cmpx->in(MemNode::Control);
-  Node* in_mem      = cmpx->in(MemNode::Memory);
-  Node* in_adr      = cmpx->in(MemNode::Address);
-  Node* in_val      = cmpx->in(MemNode::ValueIn);
-  Node* in_expected = cmpx->in(LoadStoreConditionalNode::ExpectedIn);
-
-  float likely                   = PROB_LIKELY(0.999);
-
-  const TypePtr *adr_type        = cmpx->get_ptr_type();
-  Compile::AliasType* alias_type = C->alias_type(adr_type);
-  int alias_idx                  = C->get_alias_index(adr_type);
-
-  // Outer check - true: continue, false: load and check
-  Node* region  = new RegionNode(3);
-  Node* phi     = new PhiNode(region, adr_type);
-
-  // Inner check - is the healed ref equal to the expected
-  Node* region2 = new RegionNode(3);
-  Node* phi2    = new PhiNode(region2, adr_type);
-
-  // Check if cmpx succeeded
-  Node* cmp     = gvn.transform(new CmpPNode(cmpx, in_expected));
-  Node* bol     = gvn.transform(new BoolNode(cmp, BoolTest::eq))->as_Bool();
-  IfNode* iff   = gvn.transform(new IfNode(in_ctrl, bol, likely, COUNT_UNKNOWN))->as_If();
-  Node* then    = gvn.transform(new IfTrueNode(iff));
-  Node* elsen   = gvn.transform(new IfFalseNode(iff));
-
-  Node* scmemproj1  = gvn.transform(new SCMemProjNode(cmpx));
-  kit->set_memory(scmemproj1, alias_idx);
-
-  // CAS fail - reload and heal oop
-  Node* reload      = kit->make_load(elsen, in_adr, TypeOopPtr::BOTTOM, T_OBJECT, MemNode::unordered);
-  Node* barrier     = gvn.transform(new LoadBarrierNode(C, elsen, scmemproj1, reload, in_adr, false, true, false));
-  Node* barrierctrl = gvn.transform(new ProjNode(barrier, LoadBarrierNode::Control));
-  Node* barrierdata = gvn.transform(new ProjNode(barrier, LoadBarrierNode::Oop));
-
-  // Check load
-  Node* tmpX    = gvn.transform(new CastP2XNode(NULL, barrierdata));
-  Node* in_expX = gvn.transform(new CastP2XNode(NULL, in_expected));
-  Node* cmp2    = gvn.transform(new CmpXNode(tmpX, in_expX));
-  Node *bol2    = gvn.transform(new BoolNode(cmp2, BoolTest::ne))->as_Bool();
-  IfNode* iff2  = gvn.transform(new IfNode(barrierctrl, bol2, likely, COUNT_UNKNOWN))->as_If();
-  Node* then2   = gvn.transform(new IfTrueNode(iff2));
-  Node* elsen2  = gvn.transform(new IfFalseNode(iff2));
-
-  // Redo CAS
-  Node* cmpx2      = gvn.transform(new CompareAndExchangePNode(elsen2, kit->memory(alias_idx), in_adr, in_val, in_expected, adr_type, cmpx->get_ptr_type(), cmpx->order()));
-  Node* scmemproj2 = gvn.transform(new SCMemProjNode(cmpx2));
-  kit->set_control(elsen2);
-  kit->set_memory(scmemproj2, alias_idx);
-
-  // Merge inner flow - check if healed oop was equal too expected.
-  region2->set_req(1, kit->control());
-  region2->set_req(2, then2);
-  phi2->set_req(1, cmpx2);
-  phi2->set_req(2, barrierdata);
-
-  // Merge outer flow - then check if first cas succeeded
-  region->set_req(1, then);
-  region->set_req(2, region2);
-  phi->set_req(1, cmpx);
-  phi->set_req(2, phi2);
-
-  gvn.transform(region2);
-  gvn.transform(phi2);
-  gvn.transform(region);
-  gvn.transform(phi);
-
-  kit->set_control(region);
-  kit->set_memory(in_mem, alias_idx);
-  kit->insert_mem_bar(Op_MemBarCPUOrder);
-
-  return phi;
-}
-
-Node* ZBarrierSetC2::load_barrier(GraphKit* kit, Node* val, Node* adr, bool weak, bool writeback, bool oop_reload_allowed) const {
-  PhaseGVN& gvn = kit->gvn();
-  Node* barrier = new LoadBarrierNode(Compile::current(), kit->control(), kit->memory(TypeRawPtr::BOTTOM), val, adr, weak, writeback, oop_reload_allowed);
-  Node* transformed_barrier = gvn.transform(barrier);
-
-  if (transformed_barrier->is_LoadBarrier()) {
-    if (barrier == transformed_barrier) {
-      kit->set_control(gvn.transform(new ProjNode(barrier, LoadBarrierNode::Control)));
-    }
-    Node* result = gvn.transform(new ProjNode(transformed_barrier, LoadBarrierNode::Oop));
-    return result;
-  } else {
-    return val;
-  }
-}
-
 static bool barrier_needed(C2Access& access) {
   return ZBarrierSet::barrier_needed(access.decorators(), access.type());
 }
@@ -695,266 +475,58 @@
   }
 
   bool weak = (access.decorators() & ON_WEAK_OOP_REF) != 0;
-
-  assert(access.is_parse_access(), "entry not supported at optimization time");
-  C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
-  GraphKit* kit = parse_access.kit();
-  PhaseGVN& gvn = kit->gvn();
-  Node* adr = access.addr().node();
-  Node* heap_base_oop = access.base();
-  bool unsafe = (access.decorators() & C2_UNSAFE_ACCESS) != 0;
-  if (unsafe) {
-    if (!ZVerifyLoadBarriers) {
-      p = load_barrier(kit, p, adr);
-    } else {
-      if (!TypePtr::NULL_PTR->higher_equal(gvn.type(heap_base_oop))) {
-        p = load_barrier(kit, p, adr);
-      } else {
-        IdealKit ideal(kit);
-        IdealVariable res(ideal);
-#define __ ideal.
-        __ declarations_done();
-        __ set(res, p);
-        __ if_then(heap_base_oop, BoolTest::ne, kit->null(), PROB_UNLIKELY(0.999)); {
-          kit->sync_kit(ideal);
-          p = load_barrier(kit, p, adr);
-          __ set(res, p);
-          __ sync_kit(kit);
-        } __ end_if();
-        kit->final_sync(ideal);
-        p = __ value(res);
-#undef __
-      }
-    }
-    return p;
-  } else {
-    return load_barrier(parse_access.kit(), p, access.addr().node(), weak, true, true);
+  if (p->isa_Load()) {
+    load_set_barrier(p->as_Load(), weak);
   }
+  return p;
 }
 
 Node* ZBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
                                                     Node* new_val, const Type* val_type) const {
   Node* result = BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, val_type);
-  if (!barrier_needed(access)) {
-    return result;
+  LoadStoreNode* lsn = result->as_LoadStore();
+  if (barrier_needed(access)) {
+    lsn->set_has_barrier();
   }
-
-  access.set_needs_pinning(false);
-  return make_cmpx_loadbarrier(access);
+  return lsn;
 }
 
 Node* ZBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
                                                      Node* new_val, const Type* value_type) const {
   Node* result = BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
-  if (!barrier_needed(access)) {
-    return result;
+  LoadStoreNode* lsn = result->as_LoadStore();
+  if (barrier_needed(access)) {
+    lsn->set_has_barrier();
   }
-
-  Node* load_store = access.raw_access();
-  bool weak_cas = (access.decorators() & C2_WEAK_CMPXCHG) != 0;
-  bool expected_is_null = (expected_val->get_ptr_type() == TypePtr::NULL_PTR);
-
-  if (!expected_is_null) {
-    if (weak_cas) {
-      access.set_needs_pinning(false);
-      load_store = make_cas_loadbarrier(access);
-    } else {
-      access.set_needs_pinning(false);
-      load_store = make_cas_loadbarrier(access);
-    }
-  }
-
-  return load_store;
+  return lsn;
 }
 
 Node* ZBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* val_type) const {
   Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, new_val, val_type);
-  if (!barrier_needed(access)) {
-    return result;
+  LoadStoreNode* lsn = result->as_LoadStore();
+  if (barrier_needed(access)) {
+    lsn->set_has_barrier();
   }
-
-  Node* load_store = access.raw_access();
-  Node* adr = access.addr().node();
-
-  assert(access.is_parse_access(), "entry not supported at optimization time");
-  C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
-  return load_barrier(parse_access.kit(), load_store, adr, false, false, false);
+  return lsn;
 }
 
 // == Macro Expansion ==
 
+// Optimized, low spill, loadbarrier variant using stub specialized on register used
 void ZBarrierSetC2::expand_loadbarrier_node(PhaseMacroExpand* phase, LoadBarrierNode* barrier) const {
-  Node* in_ctrl = barrier->in(LoadBarrierNode::Control);
-  Node* in_mem  = barrier->in(LoadBarrierNode::Memory);
-  Node* in_val  = barrier->in(LoadBarrierNode::Oop);
-  Node* in_adr  = barrier->in(LoadBarrierNode::Address);
-
-  Node* out_ctrl = barrier->proj_out(LoadBarrierNode::Control);
-  Node* out_res  = barrier->proj_out(LoadBarrierNode::Oop);
-
-  PhaseIterGVN &igvn = phase->igvn();
-
-  if (ZVerifyLoadBarriers) {
-    igvn.replace_node(out_res, in_val);
-    igvn.replace_node(out_ctrl, in_ctrl);
-    return;
-  }
-
-  if (barrier->can_be_eliminated()) {
-    // Clone and pin the load for this barrier below the dominating
-    // barrier: the load cannot be allowed to float above the
-    // dominating barrier
-    Node* load = in_val;
-
-    if (load->is_Load()) {
-      Node* new_load = load->clone();
-      Node* addp = new_load->in(MemNode::Address);
-      assert(addp->is_AddP() || addp->is_Phi() || addp->is_Load(), "bad address");
-      Node* cast = new CastPPNode(addp, igvn.type(addp), true);
-      Node* ctrl = NULL;
-      Node* similar = barrier->in(LoadBarrierNode::Similar);
-      if (similar->is_Phi()) {
-        // already expanded
-        ctrl = similar->in(0);
-      } else {
-        assert(similar->is_Proj() && similar->in(0)->is_LoadBarrier(), "unexpected graph shape");
-        ctrl = similar->in(0)->as_LoadBarrier()->proj_out(LoadBarrierNode::Control);
-      }
-      assert(ctrl != NULL, "bad control");
-      cast->set_req(0, ctrl);
-      igvn.transform(cast);
-      new_load->set_req(MemNode::Address, cast);
-      igvn.transform(new_load);
-
-      igvn.replace_node(out_res, new_load);
-      igvn.replace_node(out_ctrl, in_ctrl);
-      return;
-    }
-    // cannot eliminate
-  }
-
-  // There are two cases that require the basic loadbarrier
-  // 1) When the writeback of a healed oop must be avoided (swap)
-  // 2) When we must guarantee that no reload of is done (swap, cas, cmpx)
-  if (!barrier->is_writeback()) {
-    assert(!barrier->oop_reload_allowed(), "writeback barriers should be marked as requires oop");
-  }
-
-  if (!barrier->oop_reload_allowed()) {
-    expand_loadbarrier_basic(phase, barrier);
-  } else {
-    expand_loadbarrier_optimized(phase, barrier);
-  }
-}
-
-// Basic loadbarrier using conventional argument passing
-void ZBarrierSetC2::expand_loadbarrier_basic(PhaseMacroExpand* phase, LoadBarrierNode *barrier) const {
   PhaseIterGVN &igvn = phase->igvn();
-
-  Node* in_ctrl = barrier->in(LoadBarrierNode::Control);
-  Node* in_mem  = barrier->in(LoadBarrierNode::Memory);
-  Node* in_val  = barrier->in(LoadBarrierNode::Oop);
-  Node* in_adr  = barrier->in(LoadBarrierNode::Address);
-
-  Node* out_ctrl = barrier->proj_out(LoadBarrierNode::Control);
-  Node* out_res  = barrier->proj_out(LoadBarrierNode::Oop);
-
   float unlikely  = PROB_UNLIKELY(0.999);
-  const Type* in_val_maybe_null_t = igvn.type(in_val);
-
-  Node* jthread = igvn.transform(new ThreadLocalNode());
-  Node* adr = phase->basic_plus_adr(jthread, in_bytes(ZThreadLocalData::address_bad_mask_offset()));
-  Node* bad_mask = igvn.transform(LoadNode::make(igvn, in_ctrl, in_mem, adr, TypeRawPtr::BOTTOM, TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
-  Node* cast = igvn.transform(new CastP2XNode(in_ctrl, in_val));
-  Node* obj_masked = igvn.transform(new AndXNode(cast, bad_mask));
-  Node* cmp = igvn.transform(new CmpXNode(obj_masked, igvn.zerocon(TypeX_X->basic_type())));
-  Node *bol = igvn.transform(new BoolNode(cmp, BoolTest::ne))->as_Bool();
-  IfNode* iff = igvn.transform(new IfNode(in_ctrl, bol, unlikely, COUNT_UNKNOWN))->as_If();
-  Node* then = igvn.transform(new IfTrueNode(iff));
-  Node* elsen = igvn.transform(new IfFalseNode(iff));
-
-  Node* result_region;
-  Node* result_val;
-
-  result_region = new RegionNode(3);
-  result_val = new PhiNode(result_region, TypeInstPtr::BOTTOM);
-
-  result_region->set_req(1, elsen);
-  Node* res = igvn.transform(new CastPPNode(in_val, in_val_maybe_null_t));
-  res->init_req(0, elsen);
-  result_val->set_req(1, res);
-
-  const TypeFunc *tf = load_barrier_Type();
-  Node* call;
-  if (barrier->is_weak()) {
-    call = new CallLeafNode(tf,
-                            ZBarrierSetRuntime::load_barrier_on_weak_oop_field_preloaded_addr(),
-                            "ZBarrierSetRuntime::load_barrier_on_weak_oop_field_preloaded",
-                            TypeRawPtr::BOTTOM);
-  } else {
-    call = new CallLeafNode(tf,
-                            ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr(),
-                            "ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded",
-                            TypeRawPtr::BOTTOM);
-  }
-
-  call->init_req(TypeFunc::Control, then);
-  call->init_req(TypeFunc::I_O    , phase->top());
-  call->init_req(TypeFunc::Memory , in_mem);
-  call->init_req(TypeFunc::FramePtr, phase->top());
-  call->init_req(TypeFunc::ReturnAdr, phase->top());
-  call->init_req(TypeFunc::Parms+0, in_val);
-  if (barrier->is_writeback()) {
-    call->init_req(TypeFunc::Parms+1, in_adr);
-  } else {
-    // When slow path is called with a null address, the healed oop will not be written back
-    call->init_req(TypeFunc::Parms+1, igvn.zerocon(T_OBJECT));
-  }
-  call = igvn.transform(call);
-
-  Node* ctrl = igvn.transform(new ProjNode(call, TypeFunc::Control));
-  res = igvn.transform(new ProjNode(call, TypeFunc::Parms));
-  res = igvn.transform(new CheckCastPPNode(ctrl, res, in_val_maybe_null_t));
-
-  result_region->set_req(2, ctrl);
-  result_val->set_req(2, res);
-
-  result_region = igvn.transform(result_region);
-  result_val = igvn.transform(result_val);
-
-  if (out_ctrl != NULL) { // Added if cond
-    igvn.replace_node(out_ctrl, result_region);
-  }
-  igvn.replace_node(out_res, result_val);
-}
-
-// Optimized, low spill, loadbarrier variant using stub specialized on register used
-void ZBarrierSetC2::expand_loadbarrier_optimized(PhaseMacroExpand* phase, LoadBarrierNode *barrier) const {
-  PhaseIterGVN &igvn = phase->igvn();
-#ifdef PRINT_NODE_TRAVERSALS
-  Node* preceding_barrier_node = barrier->in(LoadBarrierNode::Oop);
-#endif
 
   Node* in_ctrl = barrier->in(LoadBarrierNode::Control);
   Node* in_mem = barrier->in(LoadBarrierNode::Memory);
   Node* in_val = barrier->in(LoadBarrierNode::Oop);
   Node* in_adr = barrier->in(LoadBarrierNode::Address);
 
-  Node* out_ctrl = barrier->proj_out(LoadBarrierNode::Control);
+  Node* out_ctrl = barrier->proj_out_or_null(LoadBarrierNode::Control);
   Node* out_res = barrier->proj_out(LoadBarrierNode::Oop);
 
   assert(barrier->in(LoadBarrierNode::Oop) != NULL, "oop to loadbarrier node cannot be null");
 
-#ifdef PRINT_NODE_TRAVERSALS
-  tty->print("\n\n\nBefore barrier optimization:\n");
-  traverse(barrier, out_ctrl, out_res, -1);
-
-  tty->print("\nBefore barrier optimization:  preceding_barrier_node\n");
-  traverse(preceding_barrier_node, out_ctrl, out_res, -1);
-#endif
-
-  float unlikely  = PROB_UNLIKELY(0.999);
-
   Node* jthread = igvn.transform(new ThreadLocalNode());
   Node* adr = phase->basic_plus_adr(jthread, in_bytes(ZThreadLocalData::address_bad_mask_offset()));
   Node* bad_mask = igvn.transform(LoadNode::make(igvn, in_ctrl, in_mem, adr,
@@ -968,17 +540,9 @@
   Node* then = igvn.transform(new IfTrueNode(iff));
   Node* elsen = igvn.transform(new IfFalseNode(iff));
 
-  Node* slow_path_surrogate;
-  if (!barrier->is_weak()) {
-    slow_path_surrogate = igvn.transform(new LoadBarrierSlowRegNode(then, in_mem, in_adr, in_val->adr_type(),
-                                                                    (const TypePtr*) in_val->bottom_type(), MemNode::unordered));
-  } else {
-    slow_path_surrogate = igvn.transform(new LoadBarrierWeakSlowRegNode(then, in_mem, in_adr, in_val->adr_type(),
-                                                                        (const TypePtr*) in_val->bottom_type(), MemNode::unordered));
-  }
+  Node* new_loadp = igvn.transform(new LoadBarrierSlowRegNode(then, in_mem, in_adr, in_val->adr_type(),
+                                                                    (const TypePtr*) in_val->bottom_type(), MemNode::unordered, barrier->is_weak()));
 
-  Node *new_loadp;
-  new_loadp = slow_path_surrogate;
   // Create the final region/phi pair to converge cntl/data paths to downstream code
   Node* result_region = igvn.transform(new RegionNode(3));
   result_region->set_req(1, then);
@@ -988,37 +552,28 @@
   result_phi->set_req(1, new_loadp);
   result_phi->set_req(2, barrier->in(LoadBarrierNode::Oop));
 
-  // Finally, connect the original outputs to the barrier region and phi to complete the expansion/substitution
-  // igvn.replace_node(out_ctrl, result_region);
-  if (out_ctrl != NULL) { // added if cond
+  if (out_ctrl != NULL) {
     igvn.replace_node(out_ctrl, result_region);
   }
   igvn.replace_node(out_res, result_phi);
 
   assert(barrier->outcnt() == 0,"LoadBarrier macro node has non-null outputs after expansion!");
 
-#ifdef PRINT_NODE_TRAVERSALS
-  tty->print("\nAfter barrier optimization:  old out_ctrl\n");
-  traverse(out_ctrl, out_ctrl, out_res, -1);
-  tty->print("\nAfter barrier optimization:  old out_res\n");
-  traverse(out_res, out_ctrl, out_res, -1);
-  tty->print("\nAfter barrier optimization:  old barrier\n");
-  traverse(barrier, out_ctrl, out_res, -1);
-  tty->print("\nAfter barrier optimization:  preceding_barrier_node\n");
-  traverse(preceding_barrier_node, result_region, result_phi, -1);
-#endif
+  igvn.remove_dead_node(barrier);
+  igvn.remove_dead_node(out_ctrl);
+  igvn.remove_dead_node(out_res);
 
   assert(is_gc_barrier_node(result_phi), "sanity");
   assert(step_over_gc_barrier(result_phi) == in_val, "sanity");
+
+  phase->C->print_method(PHASE_BARRIER_EXPANSION, 4, barrier->_idx);
 }
 
 bool ZBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
   ZBarrierSetC2State* s = state();
   if (s->load_barrier_count() > 0) {
     PhaseMacroExpand macro(igvn);
-#ifdef ASSERT
-    verify_gc_barriers(false);
-#endif
+
     int skipped = 0;
     while (s->load_barrier_count() > skipped) {
       int load_barrier_count = s->load_barrier_count();
@@ -1059,374 +614,6 @@
   return false;
 }
 
-// == Loop optimization ==
-
-static bool replace_with_dominating_barrier(PhaseIdealLoop* phase, LoadBarrierNode* lb, bool last_round) {
-  PhaseIterGVN &igvn = phase->igvn();
-  Compile* C = Compile::current();
-
-  LoadBarrierNode* lb2 = lb->has_dominating_barrier(phase, false, last_round);
-  if (lb2 == NULL) {
-    return false;
-  }
-
-  if (lb->in(LoadBarrierNode::Oop) != lb2->in(LoadBarrierNode::Oop)) {
-    assert(lb->in(LoadBarrierNode::Address) == lb2->in(LoadBarrierNode::Address), "Invalid address");
-    igvn.replace_input_of(lb, LoadBarrierNode::Similar, lb2->proj_out(LoadBarrierNode::Oop));
-    C->set_major_progress();
-    return false;
-  }
-
-  // That transformation may cause the Similar edge on dominated load barriers to be invalid
-  lb->fix_similar_in_uses(&igvn);
-
-  Node* val = lb->proj_out(LoadBarrierNode::Oop);
-  assert(lb2->has_true_uses(), "Invalid uses");
-  assert(lb2->in(LoadBarrierNode::Oop) == lb->in(LoadBarrierNode::Oop), "Invalid oop");
-  phase->lazy_update(lb, lb->in(LoadBarrierNode::Control));
-  phase->lazy_replace(lb->proj_out(LoadBarrierNode::Control), lb->in(LoadBarrierNode::Control));
-  igvn.replace_node(val, lb2->proj_out(LoadBarrierNode::Oop));
-
-  return true;
-}
-
-static Node* find_dominating_memory(PhaseIdealLoop* phase, Node* mem, Node* dom, int i) {
-  assert(dom->is_Region() || i == -1, "");
-
-  Node* m = mem;
-  while(phase->is_dominator(dom, phase->has_ctrl(m) ? phase->get_ctrl(m) : m->in(0))) {
-    if (m->is_Mem()) {
-      assert(m->as_Mem()->adr_type() == TypeRawPtr::BOTTOM, "");
-      m = m->in(MemNode::Memory);
-    } else if (m->is_MergeMem()) {
-      m = m->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
-    } else if (m->is_Phi()) {
-      if (m->in(0) == dom && i != -1) {
-        m = m->in(i);
-        break;
-      } else {
-        m = m->in(LoopNode::EntryControl);
-      }
-    } else if (m->is_Proj()) {
-      m = m->in(0);
-    } else if (m->is_SafePoint() || m->is_MemBar()) {
-      m = m->in(TypeFunc::Memory);
-    } else {
-#ifdef ASSERT
-      m->dump();
-#endif
-      ShouldNotReachHere();
-    }
-  }
-
-  return m;
-}
-
-static LoadBarrierNode* clone_load_barrier(PhaseIdealLoop* phase, LoadBarrierNode* lb, Node* ctl, Node* mem, Node* oop_in) {
-  PhaseIterGVN &igvn = phase->igvn();
-  Compile* C = Compile::current();
-  Node* the_clone = lb->clone();
-  the_clone->set_req(LoadBarrierNode::Control, ctl);
-  the_clone->set_req(LoadBarrierNode::Memory, mem);
-  if (oop_in != NULL) {
-    the_clone->set_req(LoadBarrierNode::Oop, oop_in);
-  }
-
-  LoadBarrierNode* new_lb = the_clone->as_LoadBarrier();
-  igvn.register_new_node_with_optimizer(new_lb);
-  IdealLoopTree *loop = phase->get_loop(new_lb->in(0));
-  phase->set_ctrl(new_lb, new_lb->in(0));
-  phase->set_loop(new_lb, loop);
-  phase->set_idom(new_lb, new_lb->in(0), phase->dom_depth(new_lb->in(0))+1);
-  if (!loop->_child) {
-    loop->_body.push(new_lb);
-  }
-
-  Node* proj_ctl = new ProjNode(new_lb, LoadBarrierNode::Control);
-  igvn.register_new_node_with_optimizer(proj_ctl);
-  phase->set_ctrl(proj_ctl, proj_ctl->in(0));
-  phase->set_loop(proj_ctl, loop);
-  phase->set_idom(proj_ctl, new_lb, phase->dom_depth(new_lb)+1);
-  if (!loop->_child) {
-    loop->_body.push(proj_ctl);
-  }
-
-  Node* proj_oop = new ProjNode(new_lb, LoadBarrierNode::Oop);
-  phase->register_new_node(proj_oop, new_lb);
-
-  if (!new_lb->in(LoadBarrierNode::Similar)->is_top()) {
-    LoadBarrierNode* similar = new_lb->in(LoadBarrierNode::Similar)->in(0)->as_LoadBarrier();
-    if (!phase->is_dominator(similar, ctl)) {
-      igvn.replace_input_of(new_lb, LoadBarrierNode::Similar, C->top());
-    }
-  }
-
-  return new_lb;
-}
-
-static void replace_barrier(PhaseIdealLoop* phase, LoadBarrierNode* lb, Node* new_val) {
-  PhaseIterGVN &igvn = phase->igvn();
-  Node* val = lb->proj_out(LoadBarrierNode::Oop);
-  igvn.replace_node(val, new_val);
-  phase->lazy_update(lb, lb->in(LoadBarrierNode::Control));
-  phase->lazy_replace(lb->proj_out(LoadBarrierNode::Control), lb->in(LoadBarrierNode::Control));
-}
-
-static bool split_barrier_thru_phi(PhaseIdealLoop* phase, LoadBarrierNode* lb) {
-  PhaseIterGVN &igvn = phase->igvn();
-  Compile* C = Compile::current();
-
-  if (lb->in(LoadBarrierNode::Oop)->is_Phi()) {
-    Node* oop_phi = lb->in(LoadBarrierNode::Oop);
-
-    if ((oop_phi->req() != 3) || (oop_phi->in(2) == oop_phi)) {
-      // Ignore phis with only one input
-      return false;
-    }
-
-    if (phase->is_dominator(phase->get_ctrl(lb->in(LoadBarrierNode::Address)),
-                            oop_phi->in(0)) && phase->get_ctrl(lb->in(LoadBarrierNode::Address)) != oop_phi->in(0)) {
-      // That transformation may cause the Similar edge on dominated load barriers to be invalid
-      lb->fix_similar_in_uses(&igvn);
-
-      RegionNode* region = oop_phi->in(0)->as_Region();
-
-      int backedge = LoopNode::LoopBackControl;
-      if (region->is_Loop() && region->in(backedge)->is_Proj() && region->in(backedge)->in(0)->is_If()) {
-        Node* c = region->in(backedge)->in(0)->in(0);
-        assert(c->unique_ctrl_out() == region->in(backedge)->in(0), "");
-        Node* oop = lb->in(LoadBarrierNode::Oop)->in(backedge);
-        Node* oop_c = phase->has_ctrl(oop) ? phase->get_ctrl(oop) : oop;
-        if (!phase->is_dominator(oop_c, c)) {
-          return false;
-        }
-      }
-
-      // If the node on the backedge above the phi is the node itself - we have a self loop.
-      // Don't clone - this will be folded later.
-      if (oop_phi->in(LoopNode::LoopBackControl) == lb->proj_out(LoadBarrierNode::Oop)) {
-        return false;
-      }
-
-      bool is_strip_mined = region->is_CountedLoop() && region->as_CountedLoop()->is_strip_mined();
-      Node *phi = oop_phi->clone();
-
-      for (uint i = 1; i < region->req(); i++) {
-        Node* ctrl = region->in(i);
-        if (ctrl != C->top()) {
-          assert(!phase->is_dominator(ctrl, region) || region->is_Loop(), "");
-
-          Node* mem = lb->in(LoadBarrierNode::Memory);
-          Node* m = find_dominating_memory(phase, mem, region, i);
-
-          if (region->is_Loop() && i == LoopNode::LoopBackControl && ctrl->is_Proj() && ctrl->in(0)->is_If()) {
-            ctrl = ctrl->in(0)->in(0);
-          } else if (region->is_Loop() && is_strip_mined) {
-            // If this is a strip mined loop, control must move above OuterStripMinedLoop
-            assert(i == LoopNode::EntryControl, "check");
-            assert(ctrl->is_OuterStripMinedLoop(), "sanity");
-            ctrl = ctrl->as_OuterStripMinedLoop()->in(LoopNode::EntryControl);
-          }
-
-          LoadBarrierNode* new_lb = clone_load_barrier(phase, lb, ctrl, m, lb->in(LoadBarrierNode::Oop)->in(i));
-          Node* out_ctrl = new_lb->proj_out(LoadBarrierNode::Control);
-
-          if (is_strip_mined && (i == LoopNode::EntryControl)) {
-            assert(region->in(i)->is_OuterStripMinedLoop(), "");
-            igvn.replace_input_of(region->in(i), i, out_ctrl);
-            phase->set_idom(region->in(i), out_ctrl, phase->dom_depth(out_ctrl));
-          } else if (ctrl == region->in(i)) {
-            igvn.replace_input_of(region, i, out_ctrl);
-            // Only update the idom if is the loop entry we are updating
-            // - A loop backedge doesn't change the idom
-            if (region->is_Loop() && i == LoopNode::EntryControl) {
-              phase->set_idom(region, out_ctrl, phase->dom_depth(out_ctrl));
-            }
-          } else {
-            Node* iff = region->in(i)->in(0);
-            igvn.replace_input_of(iff, 0, out_ctrl);
-            phase->set_idom(iff, out_ctrl, phase->dom_depth(out_ctrl)+1);
-          }
-          phi->set_req(i, new_lb->proj_out(LoadBarrierNode::Oop));
-        }
-      }
-      phase->register_new_node(phi, region);
-      replace_barrier(phase, lb, phi);
-
-      if (region->is_Loop()) {
-        // Load barrier moved to the back edge of the Loop may now
-        // have a safepoint on the path to the barrier on the Similar
-        // edge
-        igvn.replace_input_of(phi->in(LoopNode::LoopBackControl)->in(0), LoadBarrierNode::Similar, C->top());
-        Node* head = region->in(LoopNode::EntryControl);
-        phase->set_idom(region, head, phase->dom_depth(head)+1);
-        phase->recompute_dom_depth();
-        if (head->is_CountedLoop() && head->as_CountedLoop()->is_main_loop()) {
-          head->as_CountedLoop()->set_normal_loop();
-        }
-      }
-
-      return true;
-    }
-  }
-
-  return false;
-}
-
-static bool move_out_of_loop(PhaseIdealLoop* phase, LoadBarrierNode* lb) {
-  PhaseIterGVN &igvn = phase->igvn();
-  IdealLoopTree *lb_loop = phase->get_loop(lb->in(0));
-  if (lb_loop != phase->ltree_root() && !lb_loop->_irreducible) {
-    Node* oop_ctrl = phase->get_ctrl(lb->in(LoadBarrierNode::Oop));
-    IdealLoopTree *oop_loop = phase->get_loop(oop_ctrl);
-    IdealLoopTree* adr_loop = phase->get_loop(phase->get_ctrl(lb->in(LoadBarrierNode::Address)));
-    if (!lb_loop->is_member(oop_loop) && !lb_loop->is_member(adr_loop)) {
-      // That transformation may cause the Similar edge on dominated load barriers to be invalid
-      lb->fix_similar_in_uses(&igvn);
-
-      Node* head = lb_loop->_head;
-      assert(head->is_Loop(), "");
-
-      if (phase->is_dominator(head, oop_ctrl)) {
-        assert(oop_ctrl->Opcode() == Op_CProj && oop_ctrl->in(0)->Opcode() == Op_NeverBranch, "");
-        assert(lb_loop->is_member(phase->get_loop(oop_ctrl->in(0)->in(0))), "");
-        return false;
-      }
-
-      if (head->is_CountedLoop()) {
-        CountedLoopNode* cloop = head->as_CountedLoop();
-        if (cloop->is_main_loop()) {
-          cloop->set_normal_loop();
-        }
-        // When we are moving barrier out of a counted loop,
-        // make sure we move it all the way out of the strip mined outer loop.
-        if (cloop->is_strip_mined()) {
-          head = cloop->outer_loop();
-        }
-      }
-
-      Node* mem = lb->in(LoadBarrierNode::Memory);
-      Node* m = find_dominating_memory(phase, mem, head, -1);
-
-      LoadBarrierNode* new_lb = clone_load_barrier(phase, lb, head->in(LoopNode::EntryControl), m, NULL);
-
-      assert(phase->idom(head) == head->in(LoopNode::EntryControl), "");
-      Node* proj_ctl = new_lb->proj_out(LoadBarrierNode::Control);
-      igvn.replace_input_of(head, LoopNode::EntryControl, proj_ctl);
-      phase->set_idom(head, proj_ctl, phase->dom_depth(proj_ctl) + 1);
-
-      replace_barrier(phase, lb, new_lb->proj_out(LoadBarrierNode::Oop));
-
-      phase->recompute_dom_depth();
-
-      return true;
-    }
-  }
-
-  return false;
-}
-
-static bool common_barriers(PhaseIdealLoop* phase, LoadBarrierNode* lb) {
-  PhaseIterGVN &igvn = phase->igvn();
-  Node* in_val = lb->in(LoadBarrierNode::Oop);
-  for (DUIterator_Fast imax, i = in_val->fast_outs(imax); i < imax; i++) {
-    Node* u = in_val->fast_out(i);
-    if (u != lb && u->is_LoadBarrier() && u->as_LoadBarrier()->has_true_uses()) {
-      Node* this_ctrl = lb->in(LoadBarrierNode::Control);
-      Node* other_ctrl = u->in(LoadBarrierNode::Control);
-
-      Node* lca = phase->dom_lca(this_ctrl, other_ctrl);
-      Node* proj1 = NULL;
-      Node* proj2 = NULL;
-      bool ok = (lb->in(LoadBarrierNode::Address) == u->in(LoadBarrierNode::Address));
-
-      while (this_ctrl != lca && ok) {
-        if (this_ctrl->in(0) != NULL &&
-            this_ctrl->in(0)->is_MultiBranch()) {
-          if (this_ctrl->in(0)->in(0) == lca) {
-            assert(proj1 == NULL, "");
-            assert(this_ctrl->is_Proj(), "");
-            proj1 = this_ctrl;
-          } else if (!(this_ctrl->in(0)->is_If() && this_ctrl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none))) {
-            ok = false;
-          }
-        }
-        this_ctrl = phase->idom(this_ctrl);
-      }
-      while (other_ctrl != lca && ok) {
-        if (other_ctrl->in(0) != NULL &&
-            other_ctrl->in(0)->is_MultiBranch()) {
-          if (other_ctrl->in(0)->in(0) == lca) {
-            assert(other_ctrl->is_Proj(), "");
-            assert(proj2 == NULL, "");
-            proj2 = other_ctrl;
-          } else if (!(other_ctrl->in(0)->is_If() && other_ctrl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none))) {
-            ok = false;
-          }
-        }
-        other_ctrl = phase->idom(other_ctrl);
-      }
-      assert(proj1 == NULL || proj2 == NULL || proj1->in(0) == proj2->in(0), "");
-      if (ok && proj1 && proj2 && proj1 != proj2 && proj1->in(0)->is_If()) {
-        // That transformation may cause the Similar edge on dominated load barriers to be invalid
-        lb->fix_similar_in_uses(&igvn);
-        u->as_LoadBarrier()->fix_similar_in_uses(&igvn);
-
-        Node* split = lca->unique_ctrl_out();
-        assert(split->in(0) == lca, "");
-
-        Node* mem = lb->in(LoadBarrierNode::Memory);
-        Node* m = find_dominating_memory(phase, mem, split, -1);
-        LoadBarrierNode* new_lb = clone_load_barrier(phase, lb, lca, m, NULL);
-
-        Node* proj_ctl = new_lb->proj_out(LoadBarrierNode::Control);
-        igvn.replace_input_of(split, 0, new_lb->proj_out(LoadBarrierNode::Control));
-        phase->set_idom(split, proj_ctl, phase->dom_depth(proj_ctl)+1);
-
-        Node* proj_oop = new_lb->proj_out(LoadBarrierNode::Oop);
-        replace_barrier(phase, lb, proj_oop);
-        replace_barrier(phase, u->as_LoadBarrier(), proj_oop);
-
-        phase->recompute_dom_depth();
-
-        return true;
-      }
-    }
-  }
-
-  return false;
-}
-
-void ZBarrierSetC2::loop_optimize_gc_barrier(PhaseIdealLoop* phase, Node* node, bool last_round) {
-  if (!Compile::current()->directive()->ZOptimizeLoadBarriersOption) {
-    return;
-  }
-
-  if (!node->is_LoadBarrier()) {
-    return;
-  }
-
-  if (!node->as_LoadBarrier()->has_true_uses()) {
-    return;
-  }
-
-  if (replace_with_dominating_barrier(phase, node->as_LoadBarrier(), last_round)) {
-    return;
-  }
-
-  if (split_barrier_thru_phi(phase, node->as_LoadBarrier())) {
-    return;
-  }
-
-  if (move_out_of_loop(phase, node->as_LoadBarrier())) {
-    return;
-  }
-
-  if (common_barriers(phase, node->as_LoadBarrier())) {
-    return;
-  }
-}
-
 Node* ZBarrierSetC2::step_over_gc_barrier(Node* c) const {
   Node* node = c;
 
@@ -1444,7 +631,7 @@
   if (node->is_Phi()) {
     PhiNode* phi = node->as_Phi();
     Node* n = phi->in(1);
-    if (n != NULL && (n->is_LoadBarrierSlowReg() ||  n->is_LoadBarrierWeakSlowReg())) {
+    if (n != NULL && n->is_LoadBarrierSlowReg()) {
       assert(c == node, "projections from step 1 should only be seen before macro expansion");
       return phi->in(2);
     }
@@ -1458,35 +645,76 @@
 }
 
 bool ZBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode) const {
-  if (opcode != Op_LoadBarrierSlowReg &&
-      opcode != Op_LoadBarrierWeakSlowReg) {
-    return false;
-  }
-
+  switch (opcode) {
+    case Op_LoadBarrier:
+      assert(0, "There should be no load barriers left");
+    case Op_ZGetAndSetP:
+    case Op_ZCompareAndExchangeP:
+    case Op_ZCompareAndSwapP:
+    case Op_ZWeakCompareAndSwapP:
+    case Op_LoadBarrierSlowReg:
 #ifdef ASSERT
-  if (VerifyOptoOopOffsets) {
-    MemNode* mem  = n->as_Mem();
-    // Check to see if address types have grounded out somehow.
-    const TypeInstPtr* tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
-    ciInstanceKlass* k = tp->klass()->as_instance_klass();
-    bool oop_offset_is_sane = k->contains_field_offset(tp->offset());
-    assert(!tp || oop_offset_is_sane, "");
+      if (VerifyOptoOopOffsets) {
+        MemNode *mem = n->as_Mem();
+        // Check to see if address types have grounded out somehow.
+        const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
+        ciInstanceKlass *k = tp->klass()->as_instance_klass();
+        bool oop_offset_is_sane = k->contains_field_offset(tp->offset());
+        assert(!tp || oop_offset_is_sane, "");
+      }
+#endif
+      return true;
+    default:
+      return false;
   }
-#endif
-
-  return true;
 }
 
 bool ZBarrierSetC2::matcher_find_shared_visit(Matcher* matcher, Matcher::MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx) const {
-  if (opcode == Op_CallLeaf &&
-      (n->as_Call()->entry_point() == ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr() ||
-       n->as_Call()->entry_point() == ZBarrierSetRuntime::load_barrier_on_weak_oop_field_preloaded_addr())) {
-    mem_op = true;
-    mem_addr_idx = TypeFunc::Parms + 1;
-    return true;
+  switch(opcode) {
+    case Op_CallLeaf:
+      if (n->as_Call()->entry_point() == ZBarrierSetRuntime::load_barrier_on_oop_field_preloaded_addr() ||
+          n->as_Call()->entry_point() == ZBarrierSetRuntime::load_barrier_on_weak_oop_field_preloaded_addr()) {
+        mem_op = true;
+        mem_addr_idx = TypeFunc::Parms + 1;
+        return true;
+      }
+      return false;
+    default:
+      return false;
   }
+}
 
-  return false;
+bool ZBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
+  switch(opcode) {
+    case Op_ZCompareAndExchangeP:
+    case Op_ZCompareAndSwapP:
+    case Op_ZWeakCompareAndSwapP: {
+      Node *mem = n->in(MemNode::Address);
+      Node *keepalive = n->in(5);
+      Node *pair1 = new BinaryNode(mem, keepalive);
+
+      Node *newval = n->in(MemNode::ValueIn);
+      Node *oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
+      Node *pair2 = new BinaryNode(oldval, newval);
+
+      n->set_req(MemNode::Address, pair1);
+      n->set_req(MemNode::ValueIn, pair2);
+      n->del_req(5);
+      n->del_req(LoadStoreConditionalNode::ExpectedIn);
+      return true;
+    }
+    case Op_ZGetAndSetP: {
+      Node *keepalive = n->in(4);
+      Node *newval = n->in(MemNode::ValueIn);
+      Node *pair = new BinaryNode(newval, keepalive);
+      n->set_req(MemNode::ValueIn, pair);
+      n->del_req(4);
+      return true;
+    }
+
+    default:
+      return false;
+  }
 }
 
 // == Verification ==
@@ -1519,16 +747,32 @@
 }
 
 void ZBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
-  if (phase == BarrierSetC2::BeforeCodeGen) return;
-  bool post_parse = phase == BarrierSetC2::BeforeOptimize;
-  verify_gc_barriers(post_parse);
+  switch(phase) {
+    case BarrierSetC2::BeforeOptimize:
+    case BarrierSetC2::BeforeLateInsertion:
+      assert(state()->load_barrier_count() == 0, "No barriers inserted yet");
+      break;
+    case BarrierSetC2::BeforeMacroExpand:
+      // Barrier placement should be set by now.
+      verify_gc_barriers(false /*post_parse*/);
+      break;
+    case BarrierSetC2::BeforeCodeGen:
+      // Barriers has been fully expanded.
+      assert(state()->load_barrier_count() == 0, "No more macro barriers");
+      break;
+    default:
+      assert(0, "Phase without verification");
+  }
 }
 
+// post_parse implies that there might be load barriers without uses after parsing
+// That only applies when adding barriers at parse time.
 void ZBarrierSetC2::verify_gc_barriers(bool post_parse) const {
   ZBarrierSetC2State* s = state();
   Compile* C = Compile::current();
   ResourceMark rm;
   VectorSet visited(Thread::current()->resource_area());
+
   for (int i = 0; i < s->load_barrier_count(); i++) {
     LoadBarrierNode* n = s->load_barrier_node(i);
 
@@ -1542,7 +786,7 @@
             n->in(LoadBarrierNode::Similar)->in(0)->in(LoadBarrierNode::Oop) != n->in(LoadBarrierNode::Oop)),
            "broken similar edge");
 
-    assert(post_parse || n->as_LoadBarrier()->has_true_uses(),
+    assert(n->as_LoadBarrier()->has_true_uses(),
            "found unneeded load barrier");
 
     // Several load barrier nodes chained through their Similar edge
@@ -1557,87 +801,833 @@
       Unique_Node_List wq;
       Node* other = n->in(LoadBarrierNode::Similar)->in(0);
       wq.push(n);
-      bool ok = true;
-      bool dom_found = false;
       for (uint next = 0; next < wq.size(); ++next) {
-        Node *n = wq.at(next);
-        assert(n->is_CFG(), "");
-        assert(!n->is_SafePoint(), "");
+        Node *nn = wq.at(next);
+        assert(nn->is_CFG(), "");
+        assert(!nn->is_SafePoint(), "");
 
-        if (n == other) {
+        if (nn == other) {
           continue;
         }
 
-        if (n->is_Region()) {
-          for (uint i = 1; i < n->req(); i++) {
-            Node* m = n->in(i);
+        if (nn->is_Region()) {
+          for (uint i = 1; i < nn->req(); i++) {
+            Node* m = nn->in(i);
             if (m != NULL) {
               wq.push(m);
             }
           }
         } else {
-          Node* m = n->in(0);
+          Node* m = nn->in(0);
           if (m != NULL) {
             wq.push(m);
           }
         }
       }
     }
+  }
+}
 
-    if (ZVerifyLoadBarriers) {
-      if ((n->is_Load() || n->is_LoadStore()) && n->bottom_type()->make_oopptr() != NULL) {
-        visited.Clear();
-        bool found = look_for_barrier(n, post_parse, visited);
-        if (!found) {
-          n->dump(1);
-          n->dump(-3);
-          stringStream ss;
-          C->method()->print_short_name(&ss);
-          tty->print_cr("-%s-", ss.as_string());
-          assert(found, "");
+#endif // end verification code
+
+static void call_catch_cleanup_one(PhaseIdealLoop* phase, LoadNode* load, Node* ctrl);
+
+// This code is cloning all uses of a load that is between a call and the catch blocks,
+// to each use.
+
+static bool fixup_uses_in_catch(PhaseIdealLoop *phase, Node *start_ctrl, Node *node) {
+
+  if (!phase->has_ctrl(node)) {
+    // This node is floating - doesn't need to be cloned.
+    assert(node != start_ctrl, "check");
+    return false;
+  }
+
+  Node* ctrl = phase->get_ctrl(node);
+  if (ctrl != start_ctrl) {
+    // We are in a successor block - the node is ok.
+    return false; // Unwind
+  }
+
+  // Process successor nodes
+  int outcnt = node->outcnt();
+  for (int i = 0; i < outcnt; i++) {
+    Node* n = node->raw_out(0);
+    assert(!n->is_LoadBarrier(), "Sanity");
+    // Calling recursively, visiting leafs first
+    fixup_uses_in_catch(phase, start_ctrl, n);
+  }
+
+  // Now all successors are outside
+  // - Clone this node to both successors
+  int no_succs = node->outcnt();
+  assert(!node->is_Store(), "Stores not expected here");
+
+  // In some very rare cases a load that doesn't need a barrier will end up here
+  // Treat it as a LoadP and the insertion of phis will be done correctly.
+  if (node->is_Load()) {
+    call_catch_cleanup_one(phase, node->as_Load(), phase->get_ctrl(node));
+  } else {
+    for (DUIterator_Fast jmax, i = node->fast_outs(jmax); i < jmax; i++) {
+      Node* use = node->fast_out(i);
+      Node* clone = node->clone();
+      assert(clone->outcnt() == 0, "");
+
+      assert(use->find_edge(node) != -1, "check");
+      phase->igvn().rehash_node_delayed(use);
+      use->replace_edge(node, clone);
+
+      Node* new_ctrl;
+      if (use->is_block_start()) {
+        new_ctrl = use;
+      } else if (use->is_CFG()) {
+        new_ctrl = use->in(0);
+        assert (new_ctrl != NULL, "");
+      } else {
+        new_ctrl = phase->get_ctrl(use);
+      }
+
+      phase->set_ctrl(clone, new_ctrl);
+
+      if (phase->C->directive()->ZTraceLoadBarriersOption) tty->print_cr("  Clone op %i as %i to control %i", node->_idx, clone->_idx, new_ctrl->_idx);
+      phase->igvn().register_new_node_with_optimizer(clone);
+      --i, --jmax;
+    }
+    assert(node->outcnt() == 0, "must be empty now");
+
+    // Node node is dead.
+    phase->igvn().remove_dead_node(node);
+  }
+  return true; // unwind - return if a use was processed
+}
+
+// Clone a load to a specific catch_proj
+static Node* clone_load_to_catchproj(PhaseIdealLoop* phase, Node* load, Node* catch_proj) {
+  Node* cloned_load = load->clone();
+  cloned_load->set_req(0, catch_proj);      // set explicit control
+  phase->set_ctrl(cloned_load, catch_proj); // update
+  if (phase->C->directive()->ZTraceLoadBarriersOption) tty->print_cr("  Clone LOAD %i as %i to control %i", load->_idx, cloned_load->_idx, catch_proj->_idx);
+  phase->igvn().register_new_node_with_optimizer(cloned_load);
+  return cloned_load;
+}
+
+static Node* get_dominating_region(PhaseIdealLoop* phase, Node* node, Node* stop) {
+  Node* region = node;
+  while (!region->isa_Region()) {
+    Node *up = phase->idom(region);
+    assert(up != region, "Must not loop");
+    assert(up != stop,   "Must not find original control");
+    region = up;
+  }
+  return region;
+}
+
+// Clone this load to each catch block
+static void call_catch_cleanup_one(PhaseIdealLoop* phase, LoadNode* load, Node* ctrl) {
+  bool trace = phase->C->directive()->ZTraceLoadBarriersOption;
+  phase->igvn().set_delay_transform(true);
+
+  // Verify pre conditions
+  assert(ctrl->isa_Proj() && ctrl->in(0)->isa_Call(), "Must be a call proj");
+  assert(ctrl->raw_out(0)->isa_Catch(), "Must be a catch");
+
+  if (ctrl->raw_out(0)->isa_Catch()->outcnt() == 1) {
+    if (trace) tty->print_cr("Cleaning up catch: Skipping load %i, call with single catch", load->_idx);
+    return;
+  }
+
+  // Process the loads successor nodes - if any is between
+  // the call and the catch blocks, they need to be cloned to.
+  // This is done recursively
+  int outcnt = load->outcnt();
+  uint index = 0;
+  for (int i = 0; i < outcnt; i++) {
+    if (index < load->outcnt()) {
+      Node *n = load->raw_out(index);
+      assert(!n->is_LoadBarrier(), "Sanity");
+      if (!fixup_uses_in_catch(phase, ctrl, n)) {
+        // if no successor was cloned, progress to next out.
+        index++;
+      }
+    }
+  }
+
+  // Now all the loads uses has been cloned down
+  // Only thing left is to clone the loads, but they must end up
+  // first in the catch blocks.
+
+  // We clone the loads oo the catch blocks only when needed.
+  // An array is used to map the catch blocks to each lazily cloned load.
+  // In that way no extra unnecessary loads are cloned.
+
+  // Any use dominated by original block must have an phi and a region added
+
+  Node* catch_node = ctrl->raw_out(0);
+  int number_of_catch_projs = catch_node->outcnt();
+  Node** proj_to_load_mapping = NEW_RESOURCE_ARRAY(Node*, number_of_catch_projs);
+  Copy::zero_to_bytes(proj_to_load_mapping, sizeof(Node*) * number_of_catch_projs);
+
+  // The phi_map is used to keep track of where phis have already been inserted
+  int phi_map_len = phase->C->unique();
+  Node** phi_map = NEW_RESOURCE_ARRAY(Node*, phi_map_len);
+  Copy::zero_to_bytes(phi_map, sizeof(Node*) * phi_map_len);
+
+  for (unsigned int i = 0; i  < load->outcnt(); i++) {
+    Node* load_use_control = NULL;
+    Node* load_use = load->raw_out(i);
+
+    if (phase->has_ctrl(load_use)) {
+      load_use_control = phase->get_ctrl(load_use);
+    } else {
+      load_use_control = load_use->in(0);
+    }
+    assert(load_use_control != NULL, "sanity");
+    if (trace) tty->print_cr("  Handling use: %i, with control: %i", load_use->_idx, load_use_control->_idx);
+
+    // Some times the loads use is a phi. For them we need to determine from which catch block
+    // the use is defined.
+    bool load_use_is_phi = false;
+    unsigned int load_use_phi_index = 0;
+    Node* phi_ctrl = NULL;
+    if (load_use->is_Phi()) {
+      // Find phi input that matches load
+      for (unsigned int u = 1; u < load_use->req(); u++) {
+        if (load_use->in(u) == load) {
+          load_use_is_phi = true;
+          load_use_phi_index = u;
+          assert(load_use->in(0)->is_Region(), "Region or broken");
+          phi_ctrl = load_use->in(0)->in(u);
+          assert(phi_ctrl->is_CFG(), "check");
+          assert(phi_ctrl != load,   "check");
+          break;
+        }
+      }
+      assert(load_use_is_phi,        "must find");
+      assert(load_use_phi_index > 0, "sanity");
+    }
+
+    // For each load use, see which catch projs dominates, create load clone lazily and reconnect
+    bool found_dominating_catchproj = false;
+    for (int c = 0; c < number_of_catch_projs; c++) {
+      Node* catchproj = catch_node->raw_out(c);
+      assert(catchproj != NULL && catchproj->isa_CatchProj(), "Sanity");
+
+      if (!phase->is_dominator(catchproj, load_use_control)) {
+        if (load_use_is_phi && phase->is_dominator(catchproj, phi_ctrl)) {
+          // The loads use is local to the catchproj.
+          // fall out and replace load with catch-local load clone.
+        } else {
+          continue;
+        }
+      }
+      assert(!found_dominating_catchproj, "Max one should match");
+
+      // Clone loads to catch projs
+      Node* load_clone = proj_to_load_mapping[c];
+      if (load_clone == NULL) {
+        load_clone = clone_load_to_catchproj(phase, load, catchproj);
+        proj_to_load_mapping[c] = load_clone;
+      }
+      phase->igvn().rehash_node_delayed(load_use);
+
+      if (load_use_is_phi) {
+        // phis are special - the load is defined from a specific control flow
+        load_use->set_req(load_use_phi_index, load_clone);
+      } else {
+        // Multipe edges can be replaced at once - on calls for example
+        load_use->replace_edge(load, load_clone);
+      }
+      --i; // more than one edge can have been removed, but the next is in later iterations
+
+      // We could break the for-loop after finding a dominating match.
+      // But keep iterating to catch any bad idom early.
+      found_dominating_catchproj = true;
+    }
+
+    // We found no single catchproj that dominated the use - The use is at a point after
+    // where control flow from multiple catch projs have merged. We will have to create
+    // phi nodes before the use and tie the output from the cloned loads together. It
+    // can be a single phi or a number of chained phis, depending on control flow
+    if (!found_dominating_catchproj) {
+
+      // Use phi-control if use is a phi
+      if (load_use_is_phi) {
+        load_use_control = phi_ctrl;
+      }
+      assert(phase->is_dominator(ctrl, load_use_control), "Common use but no dominator");
+
+      // Clone a load on all paths
+      for (int c = 0; c < number_of_catch_projs; c++) {
+        Node* catchproj = catch_node->raw_out(c);
+        Node* load_clone = proj_to_load_mapping[c];
+        if (load_clone == NULL) {
+          load_clone = clone_load_to_catchproj(phase, load, catchproj);
+          proj_to_load_mapping[c] = load_clone;
+        }
+      }
+
+      // Move up dominator tree from use until dom front is reached
+      Node* next_region = get_dominating_region(phase, load_use_control, ctrl);
+      while (phase->idom(next_region) != catch_node) {
+        next_region = phase->idom(next_region);
+        if (trace) tty->print_cr("Moving up idom to region ctrl %i", next_region->_idx);
+      }
+      assert(phase->is_dominator(catch_node, next_region), "Sanity");
+
+      // Create or reuse phi node that collect all cloned loads and feed it to the use.
+      Node* test_phi = phi_map[next_region->_idx];
+      if ((test_phi != NULL) && test_phi->is_Phi()) {
+        // Reuse an already created phi
+        if (trace) tty->print_cr("    Using cached Phi %i on load_use %i", test_phi->_idx, load_use->_idx);
+        phase->igvn().rehash_node_delayed(load_use);
+        load_use->replace_edge(load, test_phi);
+        // Now this use is done
+      } else {
+        // Otherwise we need to create one or more phis
+        PhiNode* next_phi = new PhiNode(next_region, load->type());
+        phi_map[next_region->_idx] = next_phi; // cache new phi
+        phase->igvn().rehash_node_delayed(load_use);
+        load_use->replace_edge(load, next_phi);
+
+        int dominators_of_region = 0;
+        do {
+          // New phi, connect to region and add all loads as in.
+          Node* region = next_region;
+          assert(region->isa_Region() && region->req() > 2, "Catch dead region nodes");
+          PhiNode* new_phi = next_phi;
+
+          if (trace) tty->print_cr("Created Phi %i on load %i with control %i", new_phi->_idx, load->_idx, region->_idx);
+
+          // Need to add all cloned loads to the phi, taking care that the right path is matched
+          dominators_of_region = 0; // reset for new region
+          for (unsigned int reg_i = 1; reg_i < region->req(); reg_i++) {
+            Node* region_pred = region->in(reg_i);
+            assert(region_pred->is_CFG(), "check");
+            bool pred_has_dominator = false;
+            for (int c = 0; c < number_of_catch_projs; c++) {
+              Node* catchproj = catch_node->raw_out(c);
+              if (phase->is_dominator(catchproj, region_pred)) {
+                new_phi->set_req(reg_i, proj_to_load_mapping[c]);
+                if (trace) tty->print_cr(" - Phi in(%i) set to load %i", reg_i, proj_to_load_mapping[c]->_idx);
+                pred_has_dominator = true;
+                dominators_of_region++;
+                break;
+              }
+            }
+
+            // Sometimes we need to chain several phis.
+            if (!pred_has_dominator) {
+              assert(dominators_of_region <= 1, "More than one region can't require extra phi");
+              if (trace) tty->print_cr(" - Region %i pred %i not dominated by catch proj", region->_idx, region_pred->_idx);
+              // Continue search on on this region_pred
+              // - walk up to next region
+              // - create a new phi and connect to first new_phi
+              next_region = get_dominating_region(phase, region_pred, ctrl);
+
+              // Lookup if there already is a phi, create a new otherwise
+              Node* test_phi = phi_map[next_region->_idx];
+              if ((test_phi != NULL) && test_phi->is_Phi()) {
+                next_phi = test_phi->isa_Phi();
+                dominators_of_region++; // record that a match was found and that we are done
+                if (trace) tty->print_cr("    Using cached phi Phi %i on control %i", next_phi->_idx, next_region->_idx);
+              } else {
+                next_phi = new PhiNode(next_region, load->type());
+                phi_map[next_region->_idx] = next_phi;
+              }
+              new_phi->set_req(reg_i, next_phi);
+            }
+          }
+
+          new_phi->set_req(0, region);
+          phase->igvn().register_new_node_with_optimizer(new_phi);
+          phase->set_ctrl(new_phi, region);
+
+          assert(dominators_of_region != 0, "Must have found one this iteration");
+        } while (dominators_of_region == 1);
+      }
+      --i;
+    }
+  } // end of loop over uses
+
+  assert(load->outcnt() == 0, "All uses should be handled");
+  phase->igvn().remove_dead_node(load);
+  phase->C->print_method(PHASE_CALL_CATCH_CLEANUP, 4, load->_idx);
+
+  // Now we should be home
+  phase->igvn().set_delay_transform(false);
+}
+
+// Sort out the loads that are between a call ant its catch blocks
+static void process_catch_cleanup_candidate(PhaseIdealLoop* phase, LoadNode* load) {
+  bool trace = phase->C->directive()->ZTraceLoadBarriersOption;
+
+  Node* ctrl = phase->get_ctrl(load);
+  if (!ctrl->is_Proj() || (ctrl->in(0) == NULL) || !ctrl->in(0)->isa_Call()) {
+    return;
+  }
+
+  Node* catch_node = ctrl->isa_Proj()->raw_out(0);
+  if (catch_node->is_Catch()) {
+    if (catch_node->outcnt() > 1) {
+      call_catch_cleanup_one(phase, load, ctrl);
+    } else {
+      if (trace) tty->print_cr("Call catch cleanup with only one catch: load %i ", load->_idx);
+    }
+  }
+}
+
+void ZBarrierSetC2::barrier_insertion_phase(Compile* C, PhaseIterGVN& igvn) const {
+  PhaseIdealLoop::optimize(igvn, LoopOptsZBarrierInsertion);
+  if (C->failing())  return;
+}
+
+bool ZBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
+
+  if (mode == LoopOptsZBarrierInsertion) {
+    // First make sure all loads between call and catch are moved to the catch block
+    clean_catch_blocks(phase);
+
+    // Then expand barriers on all loads
+    insert_load_barriers(phase);
+
+    // Handle all Unsafe that need barriers.
+    insert_barriers_on_unsafe(phase);
+
+    phase->C->clear_major_progress();
+    return true;
+  } else {
+    return false;
+  }
+}
+
+static bool can_simplify_cas(LoadStoreNode* node) {
+  if (node->isa_LoadStoreConditional()) {
+    Node *expected_in = node->as_LoadStoreConditional()->in(LoadStoreConditionalNode::ExpectedIn);
+    return (expected_in->get_ptr_type() == TypePtr::NULL_PTR);
+  } else {
+    return false;
+  }
+}
+
+static void insert_barrier_before_unsafe(PhaseIdealLoop* phase, LoadStoreNode* old_node) {
+
+  Compile *C = phase->C;
+  PhaseIterGVN &igvn = phase->igvn();
+  LoadStoreNode* zclone = NULL;
+  bool is_weak = false;
+
+  Node *in_ctrl = old_node->in(MemNode::Control);
+  Node *in_mem  = old_node->in(MemNode::Memory);
+  Node *in_adr  = old_node->in(MemNode::Address);
+  Node *in_val  = old_node->in(MemNode::ValueIn);
+  const TypePtr *adr_type = old_node->adr_type();
+  const TypePtr* load_type = TypeOopPtr::BOTTOM; // The type for the load we are adding
+
+  switch (old_node->Opcode()) {
+    case Op_CompareAndExchangeP: {
+      zclone = new ZCompareAndExchangePNode(in_ctrl, in_mem, in_adr, in_val, old_node->in(LoadStoreConditionalNode::ExpectedIn),
+              adr_type, old_node->get_ptr_type(), ((CompareAndExchangeNode*)old_node)->order());
+      load_type = old_node->bottom_type()->is_ptr();
+      break;
+    }
+    case Op_WeakCompareAndSwapP: {
+      if (can_simplify_cas(old_node)) {
+        break;
+      }
+      is_weak  = true;
+      zclone = new ZWeakCompareAndSwapPNode(in_ctrl, in_mem, in_adr, in_val, old_node->in(LoadStoreConditionalNode::ExpectedIn),
+              ((CompareAndSwapNode*)old_node)->order());
+      adr_type = TypePtr::BOTTOM;
+      break;
+    }
+    case Op_CompareAndSwapP: {
+      if (can_simplify_cas(old_node)) {
+        break;
+      }
+      zclone = new ZCompareAndSwapPNode(in_ctrl, in_mem, in_adr, in_val, old_node->in(LoadStoreConditionalNode::ExpectedIn),
+              ((CompareAndSwapNode*)old_node)->order());
+      adr_type = TypePtr::BOTTOM;
+      break;
+    }
+    case Op_GetAndSetP: {
+      zclone = new ZGetAndSetPNode(in_ctrl, in_mem, in_adr, in_val, old_node->adr_type(), old_node->get_ptr_type());
+      load_type = old_node->bottom_type()->is_ptr();
+      break;
+    }
+  }
+  if (zclone != NULL) {
+    igvn.register_new_node_with_optimizer(zclone, old_node);
+
+    // Make load
+    LoadPNode *load = new LoadPNode(NULL, in_mem, in_adr, adr_type, load_type, MemNode::unordered,
+                                    LoadNode::DependsOnlyOnTest);
+    load_set_expanded_barrier(load);
+    igvn.register_new_node_with_optimizer(load);
+    igvn.replace_node(old_node, zclone);
+
+    Node *barrier = new LoadBarrierNode(C, NULL, in_mem, load, in_adr, is_weak);
+    Node *barrier_val = new ProjNode(barrier, LoadBarrierNode::Oop);
+    Node *barrier_ctrl = new ProjNode(barrier, LoadBarrierNode::Control);
+
+    igvn.register_new_node_with_optimizer(barrier);
+    igvn.register_new_node_with_optimizer(barrier_val);
+    igvn.register_new_node_with_optimizer(barrier_ctrl);
+
+    // loop over all of in_ctrl usages and move to barrier_ctrl
+    for (DUIterator_Last imin, i = in_ctrl->last_outs(imin); i >= imin; --i) {
+      Node *use = in_ctrl->last_out(i);
+      uint l;
+      for (l = 0; use->in(l) != in_ctrl; l++) {}
+      igvn.replace_input_of(use, l, barrier_ctrl);
+    }
+
+    load->set_req(MemNode::Control, in_ctrl);
+    barrier->set_req(LoadBarrierNode::Control, in_ctrl);
+    zclone->add_req(barrier_val); // add req as keep alive.
+
+    C->print_method(PHASE_ADD_UNSAFE_BARRIER, 4, zclone->_idx);
+  }
+}
+
+void ZBarrierSetC2::insert_barriers_on_unsafe(PhaseIdealLoop* phase) const {
+  Compile *C = phase->C;
+  PhaseIterGVN &igvn = phase->igvn();
+  uint new_ids = C->unique();
+  VectorSet visited(Thread::current()->resource_area());
+  GrowableArray<Node *> nodeStack(Thread::current()->resource_area(), 0, 0, NULL);
+  nodeStack.push(C->root());
+  visited.test_set(C->root()->_idx);
+
+  // Traverse all nodes, visit all unsafe ops that require a barrier
+  while (nodeStack.length() > 0) {
+    Node *n = nodeStack.pop();
+
+    bool is_old_node = (n->_idx < new_ids); // don't process nodes that were created during cleanup
+    if (is_old_node) {
+      if (n->is_LoadStore()) {
+        LoadStoreNode* lsn = n->as_LoadStore();
+        if (lsn->has_barrier()) {
+          BasicType bt = lsn->in(MemNode::Address)->bottom_type()->basic_type();
+          assert ((bt == T_OBJECT || bt == T_ARRAY), "Sanity test");
+          insert_barrier_before_unsafe(phase, lsn);
+        }
+      }
+    }
+    for (uint i = 0; i < n->len(); i++) {
+      if (n->in(i)) {
+        if (!visited.test_set(n->in(i)->_idx)) {
+          nodeStack.push(n->in(i));
+        }
+      }
+    }
+  }
+
+  igvn.optimize();
+  C->print_method(PHASE_ADD_UNSAFE_BARRIER, 2);
+}
+
+// The purpose of ZBarrierSetC2::clean_catch_blocks is to prepare the IR for
+// splicing in load barrier nodes.
+//
+// The problem is that we might have instructions between a call and its catch nodes.
+// (This is usually handled in PhaseCFG:call_catch_cleanup, which clones mach nodes in
+// already scheduled blocks.) We can't have loads that require barriers there,
+// because we need to splice in new control flow, and that would violate the IR.
+//
+// clean_catch_blocks find all Loads that require a barrier and clone them and any
+// dependent instructions to each use. The loads must be in the beginning of the catch block
+// before any store.
+//
+// Sometimes the loads use will be at a place dominated by all catch blocks, then we need
+// a load in each catch block, and a Phi at the dominated use.
+
+void ZBarrierSetC2::clean_catch_blocks(PhaseIdealLoop* phase) const {
+
+  Compile *C = phase->C;
+  uint new_ids = C->unique();
+  PhaseIterGVN &igvn = phase->igvn();
+  VectorSet visited(Thread::current()->resource_area());
+  GrowableArray<Node *> nodeStack(Thread::current()->resource_area(), 0, 0, NULL);
+  nodeStack.push(C->root());
+  visited.test_set(C->root()->_idx);
+
+  // Traverse all nodes, visit all loads that require a barrier
+  while(nodeStack.length() > 0) {
+    Node *n = nodeStack.pop();
+
+    for (uint i = 0; i < n->len(); i++) {
+      if (n->in(i)) {
+        if (!visited.test_set(n->in(i)->_idx)) {
+          nodeStack.push(n->in(i));
+        }
+      }
+    }
+
+    bool is_old_node = (n->_idx < new_ids); // don't process nodes that were created during cleanup
+    if (n->is_Load() && is_old_node) {
+      LoadNode* load = n->isa_Load();
+      // only care about loads that will have a barrier
+      if (load_require_barrier(load)) {
+        process_catch_cleanup_candidate(phase, load);
+      }
+    }
+  }
+
+  C->print_method(PHASE_CALL_CATCH_CLEANUP, 2);
+}
+
+class DomDepthCompareClosure : public CompareClosure<LoadNode*> {
+  PhaseIdealLoop* _phase;
+
+public:
+  DomDepthCompareClosure(PhaseIdealLoop* phase) : _phase(phase) { }
+
+  int do_compare(LoadNode* const &n1, LoadNode* const &n2) {
+    int d1 = _phase->dom_depth(_phase->get_ctrl(n1));
+    int d2 = _phase->dom_depth(_phase->get_ctrl(n2));
+    if (d1 == d2) {
+      // Compare index if the depth is the same, ensures all entries are unique.
+      return n1->_idx - n2->_idx;
+    } else {
+      return d2 - d1;
+    }
+  }
+};
+
+// Traverse graph and add all loadPs to list, sorted by dom depth
+void gather_loadnodes_sorted(PhaseIdealLoop* phase, GrowableArray<LoadNode*>* loadList) {
+
+  VectorSet visited(Thread::current()->resource_area());
+  GrowableArray<Node *> nodeStack(Thread::current()->resource_area(), 0, 0, NULL);
+  DomDepthCompareClosure ddcc(phase);
+
+  nodeStack.push(phase->C->root());
+  while(nodeStack.length() > 0) {
+    Node *n = nodeStack.pop();
+    if (visited.test(n->_idx)) {
+      continue;
+    }
+
+    if (n->isa_Load()) {
+      LoadNode *load = n->as_Load();
+      if (load_require_barrier(load)) {
+        assert(phase->get_ctrl(load) != NULL, "sanity");
+        assert(phase->dom_depth(phase->get_ctrl(load)) != 0, "sanity");
+        loadList->insert_sorted(&ddcc, load);
+      }
+    }
+
+    visited.set(n->_idx);
+    for (uint i = 0; i < n->req(); i++) {
+      if (n->in(i)) {
+        if (!visited.test(n->in(i)->_idx)) {
+          nodeStack.push(n->in(i));
         }
       }
     }
   }
 }
 
-#endif
+// Add LoadBarriers to all LoadPs
+void ZBarrierSetC2::insert_load_barriers(PhaseIdealLoop* phase) const {
+
+  bool trace = phase->C->directive()->ZTraceLoadBarriersOption;
+  GrowableArray<LoadNode *> loadList(Thread::current()->resource_area(), 0, 0, NULL);
+  gather_loadnodes_sorted(phase, &loadList);
+
+  PhaseIterGVN &igvn = phase->igvn();
+  int count = 0;
+
+  for (GrowableArrayIterator<LoadNode *> loadIter = loadList.begin(); loadIter != loadList.end(); ++loadIter) {
+    LoadNode *load = *loadIter;
 
-bool ZBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
-  switch (opcode) {
-    case Op_LoadBarrierSlowReg:
-    case Op_LoadBarrierWeakSlowReg:
-      conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
-      return true;
+    if (load_has_expanded_barrier(load)) {
+      continue;
+    }
 
-    case Op_Proj:
-      if (n->as_Proj()->_con != LoadBarrierNode::Oop || !n->in(0)->is_LoadBarrier()) {
-        return false;
+    do {
+      // Insert a barrier on a loadP
+      // if another load is found that needs to be expanded first, retry on that one
+      LoadNode* result = insert_one_loadbarrier(phase, load, phase->get_ctrl(load));
+      while (result != NULL) {
+        result = insert_one_loadbarrier(phase, result, phase->get_ctrl(result));
       }
-      conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0)->in(LoadBarrierNode::Oop), delayed_worklist);
-      return true;
+    } while (!load_has_expanded_barrier(load));
   }
 
-  return false;
+  phase->C->print_method(PHASE_INSERT_BARRIER, 2);
+}
+
+void push_antidependent_stores(PhaseIdealLoop* phase, Node_Stack& nodestack, LoadNode* start_load) {
+  // push all stores on the same mem, that can_alias
+  // Any load found must be handled first
+  PhaseIterGVN &igvn = phase->igvn();
+  int load_alias_idx = igvn.C->get_alias_index(start_load->adr_type());
+
+  Node *mem = start_load->in(1);
+  for (DUIterator_Fast imax, u = mem->fast_outs(imax); u < imax; u++) {
+    Node *mem_use = mem->fast_out(u);
+
+    if (mem_use == start_load) continue;
+    if (!mem_use->is_Store()) continue;
+    if (!phase->has_ctrl(mem_use)) continue;
+    if (phase->get_ctrl(mem_use) != phase->get_ctrl(start_load)) continue;
+
+    // add any aliasing store in this block
+    StoreNode *store = mem_use->isa_Store();
+    const TypePtr *adr_type = store->adr_type();
+    if (igvn.C->can_alias(adr_type, load_alias_idx)) {
+      nodestack.push(store, 0);
+    }
+  }
+}
+
+LoadNode* ZBarrierSetC2::insert_one_loadbarrier(PhaseIdealLoop* phase, LoadNode* start_load, Node* ctrl) const {
+  bool trace = phase->C->directive()->ZTraceLoadBarriersOption;
+  PhaseIterGVN &igvn = phase->igvn();
+
+  // Check for other loadPs at the same loop depth that is reachable by a DFS
+  // - if found - return it. It needs to be inserted first
+  // - otherwise proceed and insert barrier
+
+  VectorSet visited(Thread::current()->resource_area());
+  Node_Stack nodestack(100);
+
+  nodestack.push(start_load, 0);
+  push_antidependent_stores(phase, nodestack, start_load);
+
+  while(!nodestack.is_empty()) {
+    Node* n = nodestack.node(); // peek
+    nodestack.pop();
+    if (visited.test(n->_idx)) {
+      continue;
+    }
+
+    if (n->is_Load() && n != start_load && load_require_barrier(n->as_Load()) && !load_has_expanded_barrier(n->as_Load())) {
+      // Found another load that needs a barrier in the same block. Must expand later loads first.
+      if (trace) tty->print_cr(" * Found LoadP %i on DFS", n->_idx);
+      return n->as_Load(); // return node that should be expanded first
+    }
+
+    if (!phase->has_ctrl(n)) continue;
+    if (phase->get_ctrl(n) != phase->get_ctrl(start_load)) continue;
+    if (n->is_Phi()) continue;
+
+    visited.set(n->_idx);
+    // push all children
+    for (DUIterator_Fast imax, ii = n->fast_outs(imax); ii < imax; ii++) {
+      Node* c = n->fast_out(ii);
+      if (c != NULL) {
+        nodestack.push(c, 0);
+      }
+    }
+  }
+
+  insert_one_loadbarrier_inner(phase, start_load, ctrl, visited);
+  return NULL;
 }
 
-bool ZBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
-  switch (opcode) {
-    case Op_LoadBarrierSlowReg:
-    case Op_LoadBarrierWeakSlowReg:
-      if (gvn->type(n)->make_ptr() == NULL) {
-        return false;
-      }
-      conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), NULL);
-      return true;
+void ZBarrierSetC2::insert_one_loadbarrier_inner(PhaseIdealLoop* phase, LoadNode* load, Node* ctrl, VectorSet visited2) const {
+  PhaseIterGVN &igvn = phase->igvn();
+  Compile* C = igvn.C;
+  bool trace = C->directive()->ZTraceLoadBarriersOption;
+
+  // create barrier
+  Node* barrier = new LoadBarrierNode(C, NULL, load->in(LoadNode::Memory), NULL, load->in(LoadNode::Address), load_has_weak_barrier(load));
+  Node* barrier_val = new ProjNode(barrier, LoadBarrierNode::Oop);
+  Node* barrier_ctrl = new ProjNode(barrier, LoadBarrierNode::Control);
+
+  if (trace) tty->print_cr("Insert load %i with barrier: %i and ctrl : %i", load->_idx, barrier->_idx, ctrl->_idx);
+
+  // Splice control
+  // - insert barrier control diamond between loads ctrl and ctrl successor on path to block end.
+  // - If control successor is a catch, step over to next.
+  Node* ctrl_succ = NULL;
+  for (DUIterator_Fast imax, j = ctrl->fast_outs(imax); j < imax; j++) {
+    Node* tmp = ctrl->fast_out(j);
 
-    case Op_Proj:
-      if (n->as_Proj()->_con != LoadBarrierNode::Oop || !n->in(0)->is_LoadBarrier()) {
-        return false;
-      }
-      conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0)->in(LoadBarrierNode::Oop), NULL);
-      return true;
+    // - CFG nodes is the ones we are going to splice (1 only!)
+    // - Phi nodes will continue to hang from the region node!
+    // - self loops should be skipped
+    if (tmp->is_Phi() || tmp == ctrl) {
+      continue;
+    }
+
+    if (tmp->is_CFG()) {
+      assert(ctrl_succ == NULL, "There can be only one");
+      ctrl_succ = tmp;
+      continue;
+    }
+  }
+
+  // Now splice control
+  assert(ctrl_succ != load, "sanity");
+  assert(ctrl_succ != NULL, "Broken IR");
+  bool found = false;
+  for(uint k = 0; k < ctrl_succ->req(); k++) {
+    if (ctrl_succ->in(k) == ctrl) {
+      assert(!found, "sanity");
+      if (trace) tty->print_cr(" Move CFG ctrl_succ %i to barrier_ctrl", ctrl_succ->_idx);
+      igvn.replace_input_of(ctrl_succ, k, barrier_ctrl);
+      found = true;
+      k--;
+    }
   }
 
-  return false;
+  // For all successors of ctrl - move all visited to become successors of barrier_ctrl instead
+  for (DUIterator_Fast imax, r = ctrl->fast_outs(imax); r < imax; r++) {
+    Node* tmp = ctrl->fast_out(r);
+    if (visited2.test(tmp->_idx) && (tmp != load)) {
+      if (trace) tty->print_cr(" Move ctrl_succ %i to barrier_ctrl", tmp->_idx);
+      igvn.replace_input_of(tmp, 0, barrier_ctrl);
+      --r; --imax;
+    }
+  }
+
+  // Move the loads user to the barrier
+  for (DUIterator_Fast imax, i = load->fast_outs(imax); i < imax; i++) {
+    Node* u = load->fast_out(i);
+    if (u->isa_LoadBarrier()) {
+      continue;
+    }
+
+    // find correct input  - replace with iterator?
+    for(uint j = 0; j < u->req(); j++) {
+      if (u->in(j) == load) {
+        igvn.replace_input_of(u, j, barrier_val);
+        --i; --imax; // Adjust the iterator of the *outer* loop
+        break; // some nodes (calls) might have several uses from the same node
+      }
+    }
+  }
+
+  // Connect barrier to load and control
+  barrier->set_req(LoadBarrierNode::Oop, load);
+  barrier->set_req(LoadBarrierNode::Control, ctrl);
+
+  igvn.rehash_node_delayed(load);
+  igvn.register_new_node_with_optimizer(barrier);
+  igvn.register_new_node_with_optimizer(barrier_val);
+  igvn.register_new_node_with_optimizer(barrier_ctrl);
+  load_set_expanded_barrier(load);
+
+  C->print_method(PHASE_INSERT_BARRIER, 3, load->_idx);
 }
+
+// The bad_mask in the ThreadLocalData shouldn't have an anti-dep-check.
+// The bad_mask address if of type TypeRawPtr, but that will alias
+// InitializeNodes until the type system is expanded.
+bool ZBarrierSetC2::needs_anti_dependence_check(const Node* node) const {
+  MachNode* mnode = node->as_Mach();
+  if (mnode != NULL) {
+    intptr_t offset = 0;
+    const TypePtr *adr_type2 = NULL;
+    const Node* base = mnode->get_base_and_disp(offset, adr_type2);
+    if ((base != NULL) &&
+        (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_ThreadLocal) &&
+        (offset == in_bytes(ZThreadLocalData::address_bad_mask_offset()))) {
+      return false;
+    }
+  }
+  return true;
+}
--- a/src/hotspot/share/gc/z/c2/zBarrierSetC2.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/c2/zBarrierSetC2.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -29,15 +29,33 @@
 #include "opto/node.hpp"
 #include "utilities/growableArray.hpp"
 
+class ZCompareAndSwapPNode : public CompareAndSwapPNode {
+public:
+    ZCompareAndSwapPNode(Node* c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : CompareAndSwapPNode(c, mem, adr, val, ex, mem_ord) { }
+    virtual int Opcode() const;
+};
+
+class ZWeakCompareAndSwapPNode : public WeakCompareAndSwapPNode {
+public:
+    ZWeakCompareAndSwapPNode(Node* c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : WeakCompareAndSwapPNode(c, mem, adr, val, ex, mem_ord) { }
+    virtual int Opcode() const;
+};
+
+class ZCompareAndExchangePNode : public CompareAndExchangePNode {
+public:
+    ZCompareAndExchangePNode(Node* c, Node *mem, Node *adr, Node *val, Node *ex, const TypePtr* at, const Type* t, MemNode::MemOrd mem_ord) : CompareAndExchangePNode(c, mem, adr, val, ex, at, t, mem_ord) { }
+    virtual int Opcode() const;
+};
+
+class ZGetAndSetPNode : public GetAndSetPNode {
+public:
+    ZGetAndSetPNode(Node* c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* t) : GetAndSetPNode(c, mem, adr, val, at, t) { }
+    virtual int Opcode() const;
+};
+
 class LoadBarrierNode : public MultiNode {
 private:
   bool _weak;               // On strong or weak oop reference
-  bool _writeback;          // Controls if the barrier writes the healed oop back to memory
-                            // A swap on a memory location must never write back the healed oop
-  bool _oop_reload_allowed; // Controls if the barrier are allowed to reload the oop from memory
-                            // before healing, otherwise both the oop and the address must be
-                            // passed to the barrier from the oop
-
   static bool is_dominator(PhaseIdealLoop* phase, bool linear_only, Node *d, Node *n);
   void push_dominated_barriers(PhaseIterGVN* igvn) const;
 
@@ -57,9 +75,7 @@
                   Node* mem,
                   Node* val,
                   Node* adr,
-                  bool weak,
-                  bool writeback,
-                  bool oop_reload_allowed);
+                  bool weak);
 
   virtual int Opcode() const;
   virtual uint size_of() const;
@@ -86,17 +102,11 @@
   bool is_weak() const {
     return _weak;
   }
-
-  bool is_writeback() const {
-    return _writeback;
-  }
-
-  bool oop_reload_allowed() const {
-    return _oop_reload_allowed;
-  }
 };
 
 class LoadBarrierSlowRegNode : public LoadPNode {
+private:
+    bool _is_weak;
 public:
   LoadBarrierSlowRegNode(Node *c,
                          Node *mem,
@@ -104,8 +114,9 @@
                          const TypePtr *at,
                          const TypePtr* t,
                          MemOrd mo,
+                         bool weak = false,
                          ControlDependency control_dependency = DependsOnlyOnTest) :
-      LoadPNode(c, mem, adr, at, t, mo, control_dependency) {
+      LoadPNode(c, mem, adr, at, t, mo, control_dependency), _is_weak(weak) {
     init_class_id(Class_LoadBarrierSlowReg);
   }
 
@@ -118,30 +129,8 @@
   }
 
   virtual int Opcode() const;
-};
 
-class LoadBarrierWeakSlowRegNode : public LoadPNode {
-public:
-  LoadBarrierWeakSlowRegNode(Node *c,
-                             Node *mem,
-                             Node *adr,
-                             const TypePtr *at,
-                             const TypePtr* t,
-                             MemOrd mo,
-                             ControlDependency control_dependency = DependsOnlyOnTest) :
-      LoadPNode(c, mem, adr, at, t, mo, control_dependency) {
-    init_class_id(Class_LoadBarrierWeakSlowReg);
-  }
-
-  virtual const char * name() {
-    return "LoadBarrierWeakSlowRegNode";
-  }
-
-  virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) {
-    return NULL;
-  }
-
-  virtual int Opcode() const;
+  bool is_weak() { return _is_weak; }
 };
 
 class ZBarrierSetC2State : public ResourceObj {
@@ -157,15 +146,17 @@
   LoadBarrierNode* load_barrier_node(int idx) const;
 };
 
+enum BarrierInfo {
+    NoBarrier       = 0,
+    RequireBarrier  = 1,
+    WeakBarrier     = 3,  // Inclusive with RequireBarrier
+    ExpandedBarrier = 4
+};
+
 class ZBarrierSetC2 : public BarrierSetC2 {
 private:
   ZBarrierSetC2State* state() const;
-  Node* make_cas_loadbarrier(C2AtomicParseAccess& access) const;
-  Node* make_cmpx_loadbarrier(C2AtomicParseAccess& access) const;
-  void expand_loadbarrier_basic(PhaseMacroExpand* phase, LoadBarrierNode *barrier) const;
   void expand_loadbarrier_node(PhaseMacroExpand* phase, LoadBarrierNode* barrier) const;
-  void expand_loadbarrier_optimized(PhaseMacroExpand* phase, LoadBarrierNode *barrier) const;
-  const TypeFunc* load_barrier_Type() const;
 
 #ifdef ASSERT
   void verify_gc_barriers(bool post_parse) const;
@@ -186,41 +177,42 @@
                                         const Type* val_type) const;
 
 public:
-  Node* load_barrier(GraphKit* kit,
-                     Node* val,
-                     Node* adr,
-                     bool weak = false,
-                     bool writeback = true,
-                     bool oop_reload_allowed = true) const;
+  virtual void* create_barrier_state(Arena* comp_arena) const;
 
-  virtual void* create_barrier_state(Arena* comp_arena) const;
   virtual bool has_load_barriers() const { return true; }
   virtual bool is_gc_barrier_node(Node* node) const;
-  virtual void eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const { }
-  virtual void eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const;
-  virtual void add_users_to_worklist(Unique_Node_List* worklist) const;
-  virtual void enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const;
+  virtual Node* step_over_gc_barrier(Node* c) const;
+
   virtual void register_potential_barrier_node(Node* node) const;
   virtual void unregister_potential_barrier_node(Node* node) const;
+  virtual void eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const { }
+  virtual void enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const;
+  virtual void eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const;
+
   virtual bool array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, ArrayCopyPhase phase) const;
-  virtual Node* step_over_gc_barrier(Node* c) const;
-  // If the BarrierSetC2 state has kept barrier nodes in its compilation unit state to be
-  // expanded later, then now is the time to do so.
-  virtual bool expand_barriers(Compile* C, PhaseIterGVN& igvn) const;
 
-  static void find_dominating_barriers(PhaseIterGVN& igvn);
-  static void loop_optimize_gc_barrier(PhaseIdealLoop* phase, Node* node, bool last_round);
-
+  virtual bool expand_barriers(Compile* C, PhaseIterGVN& igvn) const;
   virtual bool final_graph_reshaping(Compile* compile, Node* n, uint opcode) const;
-
   virtual bool matcher_find_shared_visit(Matcher* matcher, Matcher::MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx) const;
+  virtual bool matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const;
+  virtual bool needs_anti_dependence_check(const Node* node) const;
 
 #ifdef ASSERT
   virtual void verify_gc_barriers(Compile* compile, CompilePhase phase) const;
 #endif
 
-  virtual bool escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const;
-  virtual bool escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const;
+  // Load barrier insertion and expansion external
+  virtual void barrier_insertion_phase(Compile* C, PhaseIterGVN &igvn) const;
+  virtual bool optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const;
+  virtual bool is_gc_specific_loop_opts_pass(LoopOptsMode mode) const { return (mode == LoopOptsZBarrierInsertion); }
+
+private:
+  // Load barrier insertion and expansion internal
+  void insert_barriers_on_unsafe(PhaseIdealLoop* phase) const;
+  void clean_catch_blocks(PhaseIdealLoop* phase) const;
+  void insert_load_barriers(PhaseIdealLoop* phase) const;
+  LoadNode* insert_one_loadbarrier(PhaseIdealLoop* phase, LoadNode* load, Node* ctrl) const;
+  void insert_one_loadbarrier_inner(PhaseIdealLoop* phase, LoadNode* load, Node* ctrl, VectorSet visited) const;
 };
 
 #endif // SHARE_GC_Z_C2_ZBARRIERSETC2_HPP
--- a/src/hotspot/share/gc/z/zHeap.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/zHeap.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -328,46 +328,9 @@
   _mark.flush_and_free(thread);
 }
 
-class ZFixupPartialLoadsClosure : public ZRootsIteratorClosure {
-public:
-  virtual void do_oop(oop* p) {
-    ZBarrier::mark_barrier_on_root_oop_field(p);
-  }
-
-  virtual void do_oop(narrowOop* p) {
-    ShouldNotReachHere();
-  }
-};
-
-class ZFixupPartialLoadsTask : public ZTask {
-private:
-  ZThreadRootsIterator _thread_roots;
-
-public:
-  ZFixupPartialLoadsTask() :
-      ZTask("ZFixupPartialLoadsTask"),
-      _thread_roots() {}
-
-  virtual void work() {
-    ZFixupPartialLoadsClosure cl;
-    _thread_roots.oops_do(&cl);
-  }
-};
-
-void ZHeap::fixup_partial_loads() {
-  ZFixupPartialLoadsTask task;
-  _workers.run_parallel(&task);
-}
-
 bool ZHeap::mark_end() {
   assert(SafepointSynchronize::is_at_safepoint(), "Should be at safepoint");
 
-  // C2 can generate code where a safepoint poll is inserted
-  // between a load and the associated load barrier. To handle
-  // this case we need to rescan the thread stack here to make
-  // sure such oops are marked.
-  fixup_partial_loads();
-
   // Try end marking
   if (!_mark.end()) {
     // Marking not completed, continue concurrent mark
@@ -508,8 +471,8 @@
 void ZHeap::object_iterate(ObjectClosure* cl, bool visit_referents) {
   assert(SafepointSynchronize::is_at_safepoint(), "Should be at safepoint");
 
-  ZHeapIterator iter(visit_referents);
-  iter.objects_do(cl);
+  ZHeapIterator iter;
+  iter.objects_do(cl, visit_referents);
 }
 
 void ZHeap::serviceability_initialize() {
--- a/src/hotspot/share/gc/z/zHeapIterator.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/zHeapIterator.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -51,18 +51,29 @@
   }
 };
 
+template <bool Concurrent, bool Weak>
 class ZHeapIteratorRootOopClosure : public ZRootsIteratorClosure {
 private:
   ZHeapIterator* const _iter;
 
+  oop load_oop(oop* p) {
+    if (Weak) {
+      return NativeAccess<AS_NO_KEEPALIVE | ON_PHANTOM_OOP_REF>::oop_load(p);
+    }
+
+    if (Concurrent) {
+      return NativeAccess<AS_NO_KEEPALIVE>::oop_load(p);
+    }
+
+    return RawAccess<>::oop_load(p);
+  }
+
 public:
   ZHeapIteratorRootOopClosure(ZHeapIterator* iter) :
       _iter(iter) {}
 
   virtual void do_oop(oop* p) {
-    // Load barrier needed here, even on non-concurrent strong roots,
-    // for the same reason we need fixup_partial_loads() in ZHeap::mark_end().
-    const oop obj = NativeAccess<AS_NO_KEEPALIVE>::oop_load(p);
+    const oop obj = load_oop(p);
     _iter->push(obj);
   }
 
@@ -71,28 +82,27 @@
   }
 };
 
+template <bool VisitReferents>
 class ZHeapIteratorOopClosure : public BasicOopIterateClosure {
 private:
   ZHeapIterator* const _iter;
   const oop            _base;
-  const bool           _visit_referents;
 
-  oop load_oop(oop* p) const {
-    if (_visit_referents) {
-      return HeapAccess<ON_UNKNOWN_OOP_REF | AS_NO_KEEPALIVE>::oop_load_at(_base, _base->field_offset(p));
-    } else {
-      return HeapAccess<AS_NO_KEEPALIVE>::oop_load(p);
+  oop load_oop(oop* p) {
+    if (VisitReferents) {
+      return HeapAccess<AS_NO_KEEPALIVE | ON_UNKNOWN_OOP_REF>::oop_load_at(_base, _base->field_offset(p));
     }
+
+    return HeapAccess<AS_NO_KEEPALIVE>::oop_load(p);
   }
 
 public:
-  ZHeapIteratorOopClosure(ZHeapIterator* iter, oop base, bool visit_referents) :
+  ZHeapIteratorOopClosure(ZHeapIterator* iter, oop base) :
       _iter(iter),
-      _base(base),
-      _visit_referents(visit_referents) {}
+      _base(base) {}
 
   virtual ReferenceIterationMode reference_iteration_mode() {
-    return _visit_referents ? DO_FIELDS : DO_FIELDS_EXCEPT_REFERENT;
+    return VisitReferents ? DO_FIELDS : DO_FIELDS_EXCEPT_REFERENT;
   }
 
   virtual void do_oop(oop* p) {
@@ -111,10 +121,9 @@
 #endif
 };
 
-ZHeapIterator::ZHeapIterator(bool visit_referents) :
+ZHeapIterator::ZHeapIterator() :
     _visit_stack(),
-    _visit_map(),
-    _visit_referents(visit_referents) {}
+    _visit_map() {}
 
 ZHeapIterator::~ZHeapIterator() {
   ZVisitMapIterator iter(&_visit_map);
@@ -162,49 +171,45 @@
   _visit_stack.push(obj);
 }
 
-void ZHeapIterator::objects_do(ObjectClosure* cl) {
-  // Note that the heap iterator visits all reachable objects, including
-  // objects that might be unreachable from the application, such as a
-  // not yet cleared JNIWeakGloablRef. However, also note that visiting
-  // the JVMTI tag map is a requirement to make sure we visit all tagged
-  // objects, even those that might now have become phantom reachable.
-  // If we didn't do this the application would have expected to see
-  // ObjectFree events for phantom reachable objects in the tag map.
-
-  ZStatTimerDisable disable;
-  ZHeapIteratorRootOopClosure root_cl(this);
+template <typename RootsIterator, bool Concurrent, bool Weak>
+void ZHeapIterator::push_roots() {
+  ZHeapIteratorRootOopClosure<Concurrent, Weak> cl(this);
+  RootsIterator roots;
+  roots.oops_do(&cl);
+}
 
-  // Push strong roots onto stack
-  {
-    ZRootsIterator roots;
-    roots.oops_do(&root_cl);
-  }
-
-  {
-    ZConcurrentRootsIterator roots;
-    roots.oops_do(&root_cl);
-  }
+template <bool VisitReferents>
+void ZHeapIterator::push_fields(oop obj) {
+  ZHeapIteratorOopClosure<VisitReferents> cl(this, obj);
+  obj->oop_iterate(&cl);
+}
 
-  // Push weak roots onto stack
-  {
-    ZWeakRootsIterator roots;
-    roots.oops_do(&root_cl);
-  }
+template <bool VisitReferents>
+void ZHeapIterator::objects_do(ObjectClosure* cl) {
+  ZStatTimerDisable disable;
 
-  {
-    ZConcurrentWeakRootsIterator roots;
-    roots.oops_do(&root_cl);
-  }
+  // Push roots to visit
+  push_roots<ZRootsIterator,               false /* Concurrent */, false /* Weak */>();
+  push_roots<ZConcurrentRootsIterator,     true  /* Concurrent */, false /* Weak */>();
+  push_roots<ZWeakRootsIterator,           false /* Concurrent */, true  /* Weak */>();
+  push_roots<ZConcurrentWeakRootsIterator, true  /* Concurrent */, true  /* Weak */>();
 
   // Drain stack
   while (!_visit_stack.is_empty()) {
     const oop obj = _visit_stack.pop();
 
-    // Visit
+    // Visit object
     cl->do_object(obj);
 
-    // Push members to visit
-    ZHeapIteratorOopClosure push_cl(this, obj, _visit_referents);
-    obj->oop_iterate(&push_cl);
+    // Push fields to visit
+    push_fields<VisitReferents>(obj);
   }
 }
+
+void ZHeapIterator::objects_do(ObjectClosure* cl, bool visit_referents) {
+  if (visit_referents) {
+    objects_do<true /* VisitReferents */>(cl);
+  } else {
+    objects_do<false /* VisitReferents */>(cl);
+  }
+}
--- a/src/hotspot/share/gc/z/zHeapIterator.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/zHeapIterator.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -32,8 +32,8 @@
 class ZHeapIteratorBitMap;
 
 class ZHeapIterator : public StackObj {
-  friend class ZHeapIteratorRootOopClosure;
-  friend class ZHeapIteratorOopClosure;
+  template<bool Concurrent, bool Weak> friend class ZHeapIteratorRootOopClosure;
+  template<bool VisitReferents> friend class ZHeapIteratorOopClosure;
 
 private:
   typedef ZGranuleMap<ZHeapIteratorBitMap*>         ZVisitMap;
@@ -42,16 +42,19 @@
 
   ZVisitStack _visit_stack;
   ZVisitMap   _visit_map;
-  const bool  _visit_referents;
 
   ZHeapIteratorBitMap* object_map(oop obj);
   void push(oop obj);
 
+  template <typename RootsIterator, bool Concurrent, bool Weak> void push_roots();
+  template <bool VisitReferents> void push_fields(oop obj);
+  template <bool VisitReferents> void objects_do(ObjectClosure* cl);
+
 public:
-  ZHeapIterator(bool visit_referents);
+  ZHeapIterator();
   ~ZHeapIterator();
 
-  void objects_do(ObjectClosure* cl);
+  void objects_do(ObjectClosure* cl, bool visit_referents);
 };
 
 #endif // SHARE_GC_Z_ZHEAPITERATOR_HPP
--- a/src/hotspot/share/gc/z/z_globals.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/gc/z/z_globals.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -82,9 +82,6 @@
   diagnostic(bool, ZVerifyForwarding, false,                                \
           "Verify forwarding tables")                                       \
                                                                             \
-  diagnostic(bool, ZOptimizeLoadBarriers, true,                             \
-          "Apply load barrier optimizations")                               \
-                                                                            \
   develop(bool, ZVerifyLoadBarriers, false,                                 \
           "Verify that reference loads are followed by barriers")
 
--- a/src/hotspot/share/jfr/dcmd/jfrDcmds.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jfr/dcmd/jfrDcmds.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -438,7 +438,13 @@
 
   jobjectArray settings = NULL;
   if (_settings.is_set()) {
-    const int length = _settings.value()->array()->length();
+    int length = _settings.value()->array()->length();
+    if (length == 1) {
+      const char* c_str = _settings.value()->array()->at(0);
+      if (strcmp(c_str, "none") == 0) {
+        length = 0;
+      }
+    }
     settings = JfrJavaSupport::new_string_array(length, CHECK);
     assert(settings != NULL, "invariant");
     for (int i = 0; i < length; ++i) {
--- a/src/hotspot/share/jfr/jni/jfrJavaCall.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jfr/jni/jfrJavaCall.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -184,7 +184,7 @@
   }
 }
 
-JfrJavaArguments::JfrJavaArguments(JavaValue* result) : _result(result), _klass(NULL), _name(NULL), _signature(NULL), _array_length(0) {
+JfrJavaArguments::JfrJavaArguments(JavaValue* result) : _result(result), _klass(NULL), _name(NULL), _signature(NULL), _array_length(-1) {
   assert(result != NULL, "invariant");
 }
 
@@ -193,7 +193,7 @@
   _klass(NULL),
   _name(NULL),
   _signature(NULL),
-  _array_length(0) {
+  _array_length(-1) {
   assert(result != NULL, "invariant");
   if (klass_name != NULL) {
     set_klass(klass_name, CHECK);
@@ -210,7 +210,7 @@
   _klass(NULL),
   _name(NULL),
   _signature(NULL),
-  _array_length(0) {
+  _array_length(-1) {
   assert(result != NULL, "invariant");
   if (klass != NULL) {
     set_klass(klass);
--- a/src/hotspot/share/jfr/jni/jfrJavaSupport.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jfr/jni/jfrJavaSupport.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -168,7 +168,7 @@
 
   const int array_length = args->array_length();
 
-  if (array_length > 0) {
+  if (array_length >= 0) {
     array_construction(args, result, klass, array_length, CHECK);
   } else {
     object_construction(args, result, klass, THREAD);
--- a/src/hotspot/share/jvmci/jvmciCodeInstaller.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciCodeInstaller.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -562,6 +562,7 @@
   metadata.set_pc_desc(_debug_recorder->pcs(), _debug_recorder->pcs_length());
   metadata.set_scopes(_debug_recorder->stream()->buffer(), _debug_recorder->data_size());
   metadata.set_exception_table(&_exception_handler_table);
+  metadata.set_implicit_exception_table(&_implicit_exception_table);
 
   RelocBuffer* reloc_buffer = metadata.get_reloc_buffer();
 
@@ -637,7 +638,7 @@
     JVMCIObject mirror = installed_code;
     nmethod* nm = NULL;
     result = runtime()->register_method(jvmci_env(), method, nm, entry_bci, &_offsets, _orig_pc_offset, &buffer,
-                                        stack_slots, _debug_recorder->_oopmaps, &_exception_handler_table,
+                                        stack_slots, _debug_recorder->_oopmaps, &_exception_handler_table, &_implicit_exception_table,
                                         compiler, _debug_recorder, _dependencies, id,
                                         has_unsafe_access, _has_wide_vector, compiled_code, mirror,
                                         failed_speculations, speculations, speculations_len);
@@ -870,6 +871,10 @@
         if (_orig_pc_offset < 0) {
           JVMCI_ERROR_OK("method contains safepoint, but has no deopt rescue slot");
         }
+        if (JVMCIENV->equals(reason, jvmci_env()->get_site_InfopointReason_IMPLICIT_EXCEPTION())) {
+          TRACE_jvmci_4("implicit exception at %i", pc_offset);
+          _implicit_exception_table.add_deoptimize(pc_offset);
+        }
       } else {
         TRACE_jvmci_4("infopoint at %i", pc_offset);
         site_Infopoint(buffer, pc_offset, site, JVMCI_CHECK_OK);
--- a/src/hotspot/share/jvmci/jvmciCodeInstaller.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciCodeInstaller.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -85,6 +85,8 @@
 
   ExceptionHandlerTable* get_exception_table() { return _exception_table; }
 
+  ImplicitExceptionTable* get_implicit_exception_table() { return _implicit_exception_table; }
+
   void set_pc_desc(PcDesc* desc, int count) {
     _pc_desc = desc;
     _nr_pc_desc = count;
@@ -105,6 +107,10 @@
     _exception_table = table;
   }
 
+  void set_implicit_exception_table(ImplicitExceptionTable* table) {
+    _implicit_exception_table = table;
+  }
+
 private:
   CodeBlob* _cb;
   PcDesc* _pc_desc;
@@ -118,6 +124,7 @@
   AOTOopRecorder* _oop_recorder;
 #endif
   ExceptionHandlerTable* _exception_table;
+  ImplicitExceptionTable* _implicit_exception_table;
 };
 
 /*
@@ -185,6 +192,7 @@
   DebugInformationRecorder* _debug_recorder;
   Dependencies*             _dependencies;
   ExceptionHandlerTable     _exception_handler_table;
+  ImplicitExceptionTable    _implicit_exception_table;
 
   bool _immutable_pic_compilation;  // Installer is called for Immutable PIC compilation.
 
--- a/src/hotspot/share/jvmci/jvmciCompilerToVM.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciCompilerToVM.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -453,6 +453,9 @@
   if (holder->is_interface()) {
     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Interface %s should be handled in Java code", holder->external_name()));
   }
+  if (method->can_be_statically_bound()) {
+    JVMCI_THROW_MSG_NULL(InternalError, err_msg("Effectively static method %s.%s should be handled in Java code", method->method_holder()->external_name(), method->external_name()));
+  }
 
   methodHandle ucm;
   {
@@ -921,6 +924,14 @@
   }
   HotSpotJVMCI::HotSpotMetaData::set_exceptionBytes(JVMCIENV, metadata_handle, exceptionArray);
 
+  ImplicitExceptionTable* implicit = code_metadata.get_implicit_exception_table();
+  int implicit_table_size = implicit->size_in_bytes();
+  JVMCIPrimitiveArray implicitExceptionArray = JVMCIENV->new_byteArray(implicit_table_size, JVMCI_CHECK_(JVMCI::cache_full));
+  if (implicit_table_size > 0) {
+    implicit->copy_bytes_to((address) HotSpotJVMCI::resolve(implicitExceptionArray)->byte_at_addr(0), implicit_table_size);
+  }
+  HotSpotJVMCI::HotSpotMetaData::set_implicitExceptionBytes(JVMCIENV, metadata_handle, implicitExceptionArray);
+
   return result;
 #else
   JVMCI_THROW_MSG_0(InternalError, "unimplemented");
--- a/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -334,6 +334,7 @@
     primarray_field(HotSpotMetaData, scopesDescBytes, "[B")                                                   \
     primarray_field(HotSpotMetaData, relocBytes, "[B")                                                        \
     primarray_field(HotSpotMetaData, exceptionBytes, "[B")                                                    \
+    primarray_field(HotSpotMetaData, implicitExceptionBytes, "[B")                                            \
     primarray_field(HotSpotMetaData, oopMaps, "[B")                                                           \
     object_field(HotSpotMetaData, metadata, "[Ljava/lang/Object;")                                            \
   end_class                                                                                                   \
--- a/src/hotspot/share/jvmci/jvmciRuntime.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciRuntime.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1339,6 +1339,18 @@
   return JVMCI::dependencies_invalid;
 }
 
+// Reports a pending exception and exits the VM.
+static void fatal_exception_in_compile(JVMCIEnv* JVMCIENV, JavaThread* thread, const char* msg) {
+  // Only report a fatal JVMCI compilation exception once
+  static volatile int report_init_failure = 0;
+  if (!report_init_failure && Atomic::cmpxchg(1, &report_init_failure, 0) == 0) {
+      tty->print_cr("%s:", msg);
+      JVMCIENV->describe_pending_exception(true);
+  }
+  JVMCIENV->clear_pending_exception();
+  before_exit(thread);
+  vm_exit(-1);
+}
 
 void JVMCIRuntime::compile_method(JVMCIEnv* JVMCIENV, JVMCICompiler* compiler, const methodHandle& method, int entry_bci) {
   JVMCI_EXCEPTION_CONTEXT
@@ -1360,9 +1372,7 @@
   HandleMark hm;
   JVMCIObject receiver = get_HotSpotJVMCIRuntime(JVMCIENV);
   if (JVMCIENV->has_pending_exception()) {
-    JVMCIENV->describe_pending_exception(true);
-    compile_state->set_failure(false, "exception getting HotSpotJVMCIRuntime object");
-    return;
+    fatal_exception_in_compile(JVMCIENV, thread, "Exception during HotSpotJVMCIRuntime initialization");
   }
   JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(method, JVMCIENV);
   if (JVMCIENV->has_pending_exception()) {
@@ -1397,16 +1407,7 @@
   } else {
     // An uncaught exception here implies failure during compiler initialization.
     // The only sensible thing to do here is to exit the VM.
-
-    // Only report initialization failure once
-    static volatile int report_init_failure = 0;
-    if (!report_init_failure && Atomic::cmpxchg(1, &report_init_failure, 0) == 0) {
-        tty->print_cr("Exception during JVMCI compiler initialization:");
-        JVMCIENV->describe_pending_exception(true);
-    }
-    JVMCIENV->clear_pending_exception();
-    before_exit((JavaThread*) THREAD);
-    vm_exit(-1);
+    fatal_exception_in_compile(JVMCIENV, thread, "Exception during JVMCI compiler initialization");
   }
   if (compiler->is_bootstrapping()) {
     compiler->set_bootstrap_compilation_request_handled();
@@ -1425,6 +1426,7 @@
                                 int frame_words,
                                 OopMapSet* oop_map_set,
                                 ExceptionHandlerTable* handler_table,
+                                ImplicitExceptionTable* implicit_exception_table,
                                 AbstractCompiler* compiler,
                                 DebugInformationRecorder* debug_info,
                                 Dependencies* dependencies,
@@ -1494,7 +1496,6 @@
       // as in C2, then it must be freed.
       //code_buffer->free_blob();
     } else {
-      ImplicitExceptionTable implicit_tbl;
       nm =  nmethod::new_nmethod(method,
                                  compile_id,
                                  entry_bci,
@@ -1502,7 +1503,7 @@
                                  orig_pc_offset,
                                  debug_info, dependencies, code_buffer,
                                  frame_words, oop_map_set,
-                                 handler_table, &implicit_tbl,
+                                 handler_table, implicit_exception_table,
                                  compiler, comp_level,
                                  speculations, speculations_len,
                                  nmethod_mirror_index, nmethod_mirror_name, failed_speculations);
--- a/src/hotspot/share/jvmci/jvmciRuntime.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/jvmci/jvmciRuntime.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -222,6 +222,7 @@
                        int                       frame_words,
                        OopMapSet*                oop_map_set,
                        ExceptionHandlerTable*    handler_table,
+                       ImplicitExceptionTable* implicit_exception_table,
                        AbstractCompiler*         compiler,
                        DebugInformationRecorder* debug_info,
                        Dependencies*             dependencies,
--- a/src/hotspot/share/memory/filemap.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/memory/filemap.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1080,7 +1080,7 @@
 }
 
 // Memory map a region in the address space.
-static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData",
+static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode",
                                             "String1", "String2", "OpenArchive1", "OpenArchive2" };
 
 char* FileMapInfo::map_regions(int regions[], char* saved_base[], size_t len) {
@@ -1094,7 +1094,7 @@
       return NULL;
     }
     if (i > 0) {
-      // We require that mc->rw->ro->md->od to be laid out consecutively, with no
+      // We require that mc->rw->ro->md to be laid out consecutively, with no
       // gaps between them. That way, we can ensure that the OS won't be able to
       // allocate any new memory spaces inside _shared_metaspace_{base,top}, which
       // would mess up the simple comparision in MetaspaceShared::is_in_shared_metaspace().
--- a/src/hotspot/share/memory/metaspaceClosure.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/memory/metaspaceClosure.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -45,7 +45,7 @@
 }
 
 void MetaspaceClosure::do_push(MetaspaceClosure::Ref* ref) {
-  if (ref->not_null()) { // FIXME: make this configurable, so DynamicArchiveBuilder mark all pointers
+  if (ref->not_null()) {
     bool read_only;
     Writability w = ref->writability();
     switch (w) {
--- a/src/hotspot/share/memory/metaspaceShared.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/memory/metaspaceShared.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -90,18 +90,17 @@
 //     rw  - read-write metadata
 //     ro  - read-only metadata and read-only tables
 //     md  - misc data (the c++ vtables)
-//     od  - optional data (original class files)
 //
 //     ca0 - closed archive heap space #0
 //     ca1 - closed archive heap space #1 (may be empty)
 //     oa0 - open archive heap space #0
 //     oa1 - open archive heap space #1 (may be empty)
 //
-// The mc, rw, ro, md and od regions are linearly allocated, starting from
-// SharedBaseAddress, in the order of mc->rw->ro->md->od. The size of these 5 regions
+// The mc, rw, ro, and md regions are linearly allocated, starting from
+// SharedBaseAddress, in the order of mc->rw->ro->md. The size of these 4 regions
 // are page-aligned, and there's no gap between any consecutive regions.
 //
-// These 5 regions are populated in the following steps:
+// These 4 regions are populated in the following steps:
 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 //     temporarily allocated outside of the shared regions. Only the method entry
 //     trampolines are written into the mc region.
@@ -110,10 +109,9 @@
 // [4] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 //     are copied into the ro region as read-only tables.
 // [5] C++ vtables are copied into the md region.
-// [6] Original class files are copied into the od region.
 //
 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
-// Their layout is independent of the other 5 regions.
+// Their layout is independent of the other 4 regions.
 
 char* DumpRegion::expand_top_to(char* newtop) {
   assert(is_allocatable(), "must be initialized and not packed");
@@ -174,7 +172,7 @@
   }
 }
 
-DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _md_region("md"), _od_region("od");
+DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _md_region("md");
 size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0;
 
 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space, address first_space_bottom) {
@@ -198,10 +196,6 @@
   return &_ro_region;
 }
 
-DumpRegion* MetaspaceShared::optional_data_dump_space() {
-  return &_od_region;
-}
-
 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
                                       ReservedSpace* rs) {
   current->pack(next);
@@ -290,10 +284,10 @@
   //
   //                              +-- SharedBaseAddress (default = 0x800000000)
   //                              v
-  // +-..---------+---------+ ... +----+----+----+----+----+---------------+
-  // |    Heap    | Archive |     | MC | RW | RO | MD | OD | class space   |
-  // +-..---------+---------+ ... +----+----+----+----+----+---------------+
-  // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB ------->|
+  // +-..---------+---------+ ... +----+----+----+----+---------------+
+  // |    Heap    | Archive |     | MC | RW | RO | MD | class space   |
+  // +-..---------+---------+ ... +----+----+----+----+---------------+
+  // |<--   MaxHeapSize  -->|     |<-- UnscaledClassSpaceMax = 4GB -->|
   //
   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
   const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
@@ -1074,7 +1068,7 @@
 
   LogMessage(cds) msg;
 
-  msg.info("Detailed metadata info (excluding od/st regions; rw stats include md/mc regions):");
+  msg.info("Detailed metadata info (excluding st regions; rw stats include md/mc regions):");
   msg.info("%s", hdr);
   msg.info("%s", sep);
   for (int type = 0; type < int(_number_of_types); type ++) {
--- a/src/hotspot/share/memory/metaspaceShared.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/memory/metaspaceShared.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -304,7 +304,6 @@
   static DumpRegion* misc_code_dump_space();
   static DumpRegion* read_write_dump_space();
   static DumpRegion* read_only_dump_space();
-  static DumpRegion* optional_data_dump_space();
   static void pack_dump_space(DumpRegion* current, DumpRegion* next,
                               ReservedSpace* rs);
 
--- a/src/hotspot/share/opto/classes.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/classes.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -196,7 +196,10 @@
 #endif
 zgcmacro(LoadBarrier)
 zgcmacro(LoadBarrierSlowReg)
-zgcmacro(LoadBarrierWeakSlowReg)
+zgcmacro(ZCompareAndSwapP)
+zgcmacro(ZWeakCompareAndSwapP)
+zgcmacro(ZCompareAndExchangeP)
+zgcmacro(ZGetAndSetP)
 macro(Lock)
 macro(Loop)
 macro(LoopLimit)
--- a/src/hotspot/share/opto/compile.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/compile.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -2211,8 +2211,8 @@
 
 #endif
 
+  BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 #ifdef ASSERT
-  BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
   bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
 #endif
 
@@ -2371,7 +2371,6 @@
     igvn = ccp;
     igvn.optimize();
   }
-
   print_method(PHASE_ITER_GVN2, 2);
 
   if (failing())  return;
@@ -2382,12 +2381,6 @@
     return;
   }
 
-#if INCLUDE_ZGC
-  if (UseZGC) {
-    ZBarrierSetC2::find_dominating_barriers(igvn);
-  }
-#endif
-
   if (failing())  return;
 
   // Ensure that major progress is now clear
@@ -2407,28 +2400,33 @@
   }
 
 #ifdef ASSERT
-  BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
-  bs->verify_gc_barriers(this, BarrierSetC2::BeforeExpand);
+  bs->verify_gc_barriers(this, BarrierSetC2::BeforeLateInsertion);
+#endif
+
+  bs->barrier_insertion_phase(C, igvn);
+  if (failing())  return;
+
+#ifdef ASSERT
+  bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
 #endif
 
   {
     TracePhase tp("macroExpand", &timers[_t_macroExpand]);
     PhaseMacroExpand  mex(igvn);
-    print_method(PHASE_BEFORE_MACRO_EXPANSION, 2);
     if (mex.expand_macro_nodes()) {
       assert(failing(), "must bail out w/ explicit message");
       return;
     }
+    print_method(PHASE_MACRO_EXPANSION, 2);
   }
 
   {
     TracePhase tp("barrierExpand", &timers[_t_barrierExpand]);
-    print_method(PHASE_BEFORE_BARRIER_EXPAND, 2);
-    BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
     if (bs->expand_barriers(this, igvn)) {
       assert(failing(), "must bail out w/ explicit message");
       return;
     }
+    print_method(PHASE_BARRIER_EXPANSION, 2);
   }
 
   if (opaque4_count() > 0) {
@@ -2824,7 +2822,7 @@
     MemBarNode* mb = n->as_MemBar();
     if (mb->trailing_store() || mb->trailing_load_store()) {
       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
-      Node* mem = mb->in(MemBarNode::Precedent);
+      Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
     } else if (mb->leading()) {
--- a/src/hotspot/share/opto/compile.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/compile.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -52,6 +52,7 @@
 class CallGenerator;
 class CloneMap;
 class ConnectionGraph;
+class IdealGraphPrinter;
 class InlineTree;
 class Int_Array;
 class LoadBarrierNode;
@@ -95,9 +96,9 @@
   LoopOptsNone,
   LoopOptsShenandoahExpand,
   LoopOptsShenandoahPostExpand,
+  LoopOptsZBarrierInsertion,
   LoopOptsSkipSplitIf,
-  LoopOptsVerify,
-  LoopOptsLastRound
+  LoopOptsVerify
 };
 
 typedef unsigned int node_idx_t;
@@ -658,6 +659,7 @@
   void          set_do_cleanup(bool z)          { _do_cleanup = z; }
   int               do_cleanup() const          { return _do_cleanup; }
   void          set_major_progress()            { _major_progress++; }
+  void          restore_major_progress(int progress) { _major_progress += progress; }
   void        clear_major_progress()            { _major_progress = 0; }
   int               max_inline_size() const     { return _max_inline_size; }
   void          set_freq_inline_size(int n)     { _freq_inline_size = n; }
@@ -747,7 +749,15 @@
     C->_latest_stage_start_counter.stamp();
   }
 
-  void print_method(CompilerPhaseType cpt, int level = 1) {
+  bool should_print(int level = 1) {
+#ifndef PRODUCT
+    return (_printer && _printer->should_print(level));
+#else
+    return false;
+#endif
+  }
+
+  void print_method(CompilerPhaseType cpt, int level = 1, int idx = 0) {
     EventCompilerPhase event;
     if (event.should_commit()) {
       event.set_starttime(C->_latest_stage_start_counter);
@@ -757,10 +767,15 @@
       event.commit();
     }
 
-
 #ifndef PRODUCT
-    if (_printer && _printer->should_print(level)) {
-      _printer->print_method(CompilerPhaseTypeHelper::to_string(cpt), level);
+    if (should_print(level)) {
+      char output[1024];
+      if (idx != 0) {
+        sprintf(output, "%s:%d", CompilerPhaseTypeHelper::to_string(cpt), idx);
+      } else {
+        sprintf(output, "%s", CompilerPhaseTypeHelper::to_string(cpt));
+      }
+      _printer->print_method(output, level);
     }
 #endif
     C->_latest_stage_start_counter.stamp();
--- a/src/hotspot/share/opto/idealGraphPrinter.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/idealGraphPrinter.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -350,14 +350,6 @@
   _xml->flush();
 }
 
-// Print indent
-void IdealGraphPrinter::print_indent() {
-  tty->print_cr("printing indent %d", _depth);
-  for (int i = 0; i < _depth; i++) {
-    _xml->print("%s", INDENT);
-  }
-}
-
 bool IdealGraphPrinter::traverse_outs() {
   return _traverse_outs;
 }
@@ -663,14 +655,16 @@
   }
 }
 
-void IdealGraphPrinter::print_method(const char *name, int level, bool clear_nodes) {
-  print(name, (Node *)C->root(), level, clear_nodes);
+void IdealGraphPrinter::print_method(const char *name, int level) {
+  if (should_print(level)) {
+    print(name, (Node *) C->root());
+  }
 }
 
 // Print current ideal graph
-void IdealGraphPrinter::print(const char *name, Node *node, int level, bool clear_nodes) {
+void IdealGraphPrinter::print(const char *name, Node *node) {
 
-  if (!_current_method || !_should_send_method || !should_print(level)) return;
+  if (!_current_method || !_should_send_method) return;
 
   // Warning, unsafe cast?
   _chaitin = (PhaseChaitin *)C->regalloc();
--- a/src/hotspot/share/opto/idealGraphPrinter.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/idealGraphPrinter.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -81,11 +81,7 @@
   static const char *METHOD_SHORT_NAME_PROPERTY;
   static const char *ASSEMBLY_ELEMENT;
 
-  elapsedTimer _walk_time;
-  elapsedTimer _output_time;
-  elapsedTimer _build_blocks_time;
-
-  static int _file_count;
+    static int _file_count;
   networkStream *_stream;
   xmlStream *_xml;
   outputStream *_output;
@@ -97,10 +93,6 @@
   bool _traverse_outs;
   Compile *C;
 
-  static void pre_node(Node* node, void *env);
-  static void post_node(Node* node, void *env);
-
-  void print_indent();
   void print_method(ciMethod *method, int bci, InlineTree *tree);
   void print_inline_tree(InlineTree *tree);
   void visit_node(Node *n, bool edges, VectorSet* temp_set);
@@ -116,7 +108,6 @@
   void tail(const char *name);
   void head(const char *name);
   void text(const char *s);
-  intptr_t get_node_id(Node *n);
   IdealGraphPrinter();
   ~IdealGraphPrinter();
 
@@ -130,9 +121,8 @@
   void print_inlining();
   void begin_method();
   void end_method();
-  void print_method(const char *name, int level=1, bool clear_nodes = false);
-  void print(const char *name, Node *root, int level=1, bool clear_nodes = false);
-  void print_xml(const char *name);
+  void print_method(const char *name, int level = 0);
+  void print(const char *name, Node *root);
   bool should_print(int level);
   void set_compile(Compile* compile) {C = compile; }
 };
--- a/src/hotspot/share/opto/lcm.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/lcm.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -171,7 +171,6 @@
     case Op_LoadL:
     case Op_LoadP:
     case Op_LoadBarrierSlowReg:
-    case Op_LoadBarrierWeakSlowReg:
     case Op_LoadN:
     case Op_LoadS:
     case Op_LoadKlass:
--- a/src/hotspot/share/opto/loopnode.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/loopnode.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -978,7 +978,7 @@
         wq.push(u);
         bool found_sfpt = false;
         for (uint next = 0; next < wq.size() && !found_sfpt; next++) {
-          Node *n = wq.at(next);
+          Node* n = wq.at(next);
           for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !found_sfpt; i++) {
             Node* u = n->fast_out(i);
             if (u == sfpt) {
@@ -992,6 +992,19 @@
         assert(found_sfpt, "no node in loop that's not input to safepoint");
       }
     }
+
+    if (UseZGC && !inner_out->in(0)->is_CountedLoopEnd()) {
+      // In some very special cases there can be a load that has no other uses than the
+      // counted loop safepoint. Then its loadbarrier will be placed between the inner
+      // loop exit and the safepoint. This is very rare
+
+      Node* ifnode = inner_out->in(1)->in(0);
+      // Region->IfTrue->If == Region->Iffalse->If
+      if (ifnode == inner_out->in(2)->in(0)) {
+        inner_out = ifnode->in(0);
+      }
+    }
+
     CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd();
     assert(cle == inner->loopexit_or_null(), "mismatch");
     bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0;
@@ -2761,7 +2774,7 @@
 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
 // its corresponding LoopNode.  If 'optimize' is true, do some loop cleanups.
 void PhaseIdealLoop::build_and_optimize(LoopOptsMode mode) {
-  bool do_split_ifs = (mode == LoopOptsDefault || mode == LoopOptsLastRound);
+  bool do_split_ifs = (mode == LoopOptsDefault);
   bool skip_loop_opts = (mode == LoopOptsNone);
 
   int old_progress = C->major_progress();
@@ -2921,9 +2934,7 @@
   build_loop_late( visited, worklist, nstack );
 
   if (_verify_only) {
-    // restore major progress flag
-    for (int i = 0; i < old_progress; i++)
-      C->set_major_progress();
+    C->restore_major_progress(old_progress);
     assert(C->unique() == unique, "verification mode made Nodes? ? ?");
     assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
     return;
@@ -2967,9 +2978,7 @@
 
   if (skip_loop_opts) {
     // restore major progress flag
-    for (int i = 0; i < old_progress; i++) {
-      C->set_major_progress();
-    }
+    C->restore_major_progress(old_progress);
 
     // Cleanup any modified bits
     _igvn.optimize();
@@ -3018,11 +3027,8 @@
   // that require basic-block info (like cloning through Phi's)
   if( SplitIfBlocks && do_split_ifs ) {
     visited.Clear();
-    split_if_with_blocks( visited, nstack, mode == LoopOptsLastRound );
+    split_if_with_blocks( visited, nstack);
     NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
-    if (mode == LoopOptsLastRound) {
-      C->set_major_progress();
-    }
   }
 
   if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
@@ -3157,8 +3163,7 @@
   _ltree_root->verify_tree(loop_verify._ltree_root, NULL);
   // Reset major-progress.  It was cleared by creating a verify version of
   // PhaseIdealLoop.
-  for( int i=0; i<old_progress; i++ )
-    C->set_major_progress();
+  C->restore_major_progress(old_progress);
 }
 
 //------------------------------verify_compare---------------------------------
@@ -4288,7 +4293,6 @@
     case Op_LoadS:
     case Op_LoadP:
     case Op_LoadBarrierSlowReg:
-    case Op_LoadBarrierWeakSlowReg:
     case Op_LoadN:
     case Op_LoadRange:
     case Op_LoadD_unaligned:
--- a/src/hotspot/share/opto/loopnode.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/loopnode.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -824,6 +824,7 @@
   // pull such a subsumed block out of the array, we write back the final
   // correct block.
   Node *get_ctrl( Node *i ) {
+
     assert(has_node(i), "");
     Node *n = get_ctrl_no_update(i);
     _nodes.map( i->_idx, (Node*)((intptr_t)n + 1) );
@@ -1306,9 +1307,9 @@
 
   // Check for aggressive application of 'split-if' optimization,
   // using basic block level info.
-  void  split_if_with_blocks     ( VectorSet &visited, Node_Stack &nstack, bool last_round );
+  void  split_if_with_blocks     ( VectorSet &visited, Node_Stack &nstack);
   Node *split_if_with_blocks_pre ( Node *n );
-  void  split_if_with_blocks_post( Node *n, bool last_round );
+  void  split_if_with_blocks_post( Node *n );
   Node *has_local_phi_input( Node *n );
   // Mark an IfNode as being dominated by a prior test,
   // without actually altering the CFG (and hence IDOM info).
--- a/src/hotspot/share/opto/loopopts.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/loopopts.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1195,11 +1195,11 @@
 // Do the real work in a non-recursive function.  CFG hackery wants to be
 // in the post-order, so it can dirty the I-DOM info and not use the dirtied
 // info.
-void PhaseIdealLoop::split_if_with_blocks_post(Node *n, bool last_round) {
+void PhaseIdealLoop::split_if_with_blocks_post(Node *n) {
 
   // Cloning Cmp through Phi's involves the split-if transform.
   // FastLock is not used by an If
-  if (n->is_Cmp() && !n->is_FastLock() && !last_round) {
+  if (n->is_Cmp() && !n->is_FastLock()) {
     Node *n_ctrl = get_ctrl(n);
     // Determine if the Node has inputs from some local Phi.
     // Returns the block to clone thru.
@@ -1451,18 +1451,12 @@
       get_loop(get_ctrl(n)) == get_loop(get_ctrl(n->in(1))) ) {
     _igvn.replace_node( n, n->in(1) );
   }
-
-#if INCLUDE_ZGC
-  if (UseZGC) {
-    ZBarrierSetC2::loop_optimize_gc_barrier(this, n, last_round);
-  }
-#endif
 }
 
 //------------------------------split_if_with_blocks---------------------------
 // Check for aggressive application of 'split-if' optimization,
 // using basic block level info.
-void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack, bool last_round) {
+void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack) {
   Node* root = C->root();
   visited.set(root->_idx); // first, mark root as visited
   // Do pre-visit work for root
@@ -1488,7 +1482,7 @@
       // All of n's children have been processed, complete post-processing.
       if (cnt != 0 && !n->is_Con()) {
         assert(has_node(n), "no dead nodes");
-        split_if_with_blocks_post(n, last_round);
+        split_if_with_blocks_post(n);
       }
       if (must_throttle_split_if()) {
         nstack.clear();
--- a/src/hotspot/share/opto/memnode.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/memnode.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -908,14 +908,6 @@
 // a load node that reads from the source array so we may be able to
 // optimize out the ArrayCopy node later.
 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
-#if INCLUDE_ZGC
-  if (UseZGC) {
-    if (bottom_type()->make_oopptr() != NULL) {
-      return NULL;
-    }
-  }
-#endif
-
   Node* ld_adr = in(MemNode::Address);
   intptr_t ld_off = 0;
   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
@@ -2811,7 +2803,8 @@
 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
   : Node(required),
     _type(rt),
-    _adr_type(at)
+    _adr_type(at),
+    _has_barrier(false)
 {
   init_req(MemNode::Control, c  );
   init_req(MemNode::Memory , mem);
@@ -3105,16 +3098,6 @@
     return NULL;
   }
 
-#if INCLUDE_ZGC
-  if (UseZGC) {
-    if (req() == (Precedent+1) && in(MemBarNode::Precedent)->in(0) != NULL && in(MemBarNode::Precedent)->in(0)->is_LoadBarrier()) {
-      Node* load_node = in(MemBarNode::Precedent)->in(0)->in(LoadBarrierNode::Oop);
-      set_req(MemBarNode::Precedent, load_node);
-      return this;
-    }
-  }
-#endif
-
   bool progress = false;
   // Eliminate volatile MemBars for scalar replaced objects.
   if (can_reshape && req() == (Precedent+1)) {
--- a/src/hotspot/share/opto/memnode.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/memnode.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -164,6 +164,7 @@
     Pinned,
     DependsOnlyOnTest
   };
+
 private:
   // LoadNode::hash() doesn't take the _control_dependency field
   // into account: If the graph already has a non-pinned LoadNode and
@@ -182,6 +183,8 @@
   // this field.
   const MemOrd _mo;
 
+  uint _barrier; // Bit field with barrier information
+
 protected:
   virtual bool cmp(const Node &n) const;
   virtual uint size_of() const; // Size is bigger
@@ -193,7 +196,7 @@
 public:
 
   LoadNode(Node *c, Node *mem, Node *adr, const TypePtr* at, const Type *rt, MemOrd mo, ControlDependency control_dependency)
-    : MemNode(c,mem,adr,at), _control_dependency(control_dependency), _mo(mo), _type(rt) {
+    : MemNode(c,mem,adr,at), _control_dependency(control_dependency), _mo(mo), _barrier(0), _type(rt) {
     init_class_id(Class_Load);
   }
   inline bool is_unordered() const { return !is_acquire(); }
@@ -262,6 +265,10 @@
   Node* convert_to_unsigned_load(PhaseGVN& gvn);
   Node* convert_to_signed_load(PhaseGVN& gvn);
 
+  void copy_barrier_info(const Node* src) { _barrier = src->as_Load()->_barrier; }
+  uint barrier_data() { return _barrier; }
+  void set_barrier_data(uint barrier_data) { _barrier |= barrier_data; }
+
 #ifndef PRODUCT
   virtual void dump_spec(outputStream *st) const;
 #endif
@@ -810,6 +817,7 @@
 private:
   const Type* const _type;      // What kind of value is loaded?
   const TypePtr* _adr_type;     // What kind of memory is being addressed?
+  bool _has_barrier;
   virtual uint size_of() const; // Size is bigger
 public:
   LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required );
@@ -822,6 +830,8 @@
 
   bool result_not_used() const;
   MemBarNode* trailing_membar() const;
+  void set_has_barrier() { _has_barrier = true; };
+  bool has_barrier() const { return _has_barrier; };
 };
 
 class LoadStoreConditionalNode : public LoadStoreNode {
--- a/src/hotspot/share/opto/node.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/node.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -546,6 +546,9 @@
   if (n->is_SafePoint()) {
     n->as_SafePoint()->clone_replaced_nodes();
   }
+  if (n->is_Load()) {
+    n->as_Load()->copy_barrier_info(this);
+  }
   return n;                     // Return the clone
 }
 
@@ -564,7 +567,6 @@
   }
 }
 
-
 //------------------------------~Node------------------------------------------
 // Fancy destructor; eagerly attempt to reclaim Node numberings and storage
 void Node::destruct() {
@@ -1454,13 +1456,16 @@
 //------------------------------needs_anti_dependence_check---------------------
 // Nodes which use memory without consuming it, hence need antidependences.
 bool Node::needs_anti_dependence_check() const {
-  if( req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0 )
+  if (req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0) {
     return false;
-  else
-    return in(1)->bottom_type()->has_memory();
+  }
+  BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
+  if (!bs->needs_anti_dependence_check(this)) {
+    return false;
+  }
+  return in(1)->bottom_type()->has_memory();
 }
 
-
 // Get an integer constant from a ConNode (or CastIINode).
 // Return a default value if there is no apparent constant here.
 const TypeInt* Node::find_int_type() const {
--- a/src/hotspot/share/opto/node.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/node.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -83,8 +83,8 @@
 class LoadNode;
 class LoadBarrierNode;
 class LoadBarrierSlowRegNode;
-class LoadBarrierWeakSlowRegNode;
 class LoadStoreNode;
+class LoadStoreConditionalNode;
 class LockNode;
 class LoopNode;
 class MachBranchNode;
@@ -688,8 +688,7 @@
     DEFINE_CLASS_ID(Mem,   Node, 4)
       DEFINE_CLASS_ID(Load,  Mem, 0)
         DEFINE_CLASS_ID(LoadVector,  Load, 0)
-          DEFINE_CLASS_ID(LoadBarrierSlowReg, Load, 1)
-          DEFINE_CLASS_ID(LoadBarrierWeakSlowReg, Load, 2)
+        DEFINE_CLASS_ID(LoadBarrierSlowReg, Load, 1)
       DEFINE_CLASS_ID(Store, Mem, 1)
         DEFINE_CLASS_ID(StoreVector, Store, 0)
       DEFINE_CLASS_ID(LoadStore, Mem, 2)
@@ -830,9 +829,9 @@
   DEFINE_CLASS_QUERY(JumpProj)
   DEFINE_CLASS_QUERY(Load)
   DEFINE_CLASS_QUERY(LoadStore)
+  DEFINE_CLASS_QUERY(LoadStoreConditional)
   DEFINE_CLASS_QUERY(LoadBarrier)
   DEFINE_CLASS_QUERY(LoadBarrierSlowReg)
-  DEFINE_CLASS_QUERY(LoadBarrierWeakSlowReg)
   DEFINE_CLASS_QUERY(Lock)
   DEFINE_CLASS_QUERY(Loop)
   DEFINE_CLASS_QUERY(Mach)
--- a/src/hotspot/share/opto/phaseX.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/phaseX.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1003,9 +1003,6 @@
         n->is_Mem() )
       add_users_to_worklist(n);
   }
-
-  BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
-  bs->add_users_to_worklist(&_worklist);
 }
 
 /**
--- a/src/hotspot/share/opto/phasetype.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/phasetype.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -52,8 +52,11 @@
   PHASE_MATCHING,
   PHASE_INCREMENTAL_INLINE,
   PHASE_INCREMENTAL_BOXING_INLINE,
-  PHASE_BEFORE_BARRIER_EXPAND,
-  PHASE_BEFORE_MACRO_EXPANSION,
+  PHASE_CALL_CATCH_CLEANUP,
+  PHASE_INSERT_BARRIER,
+  PHASE_MACRO_EXPANSION,
+  PHASE_BARRIER_EXPANSION,
+  PHASE_ADD_UNSAFE_BARRIER,
   PHASE_END,
   PHASE_FAILURE,
 
@@ -90,8 +93,11 @@
       case PHASE_MATCHING:                   return "After matching";
       case PHASE_INCREMENTAL_INLINE:         return "Incremental Inline";
       case PHASE_INCREMENTAL_BOXING_INLINE:  return "Incremental Boxing Inline";
-      case PHASE_BEFORE_BARRIER_EXPAND:      return "Before Barrier Expand";
-      case PHASE_BEFORE_MACRO_EXPANSION:     return "Before macro expansion";
+      case PHASE_CALL_CATCH_CLEANUP:         return "Call catch cleanup";
+      case PHASE_INSERT_BARRIER:             return "Insert barrier";
+      case PHASE_MACRO_EXPANSION:            return "Macro expand";
+      case PHASE_BARRIER_EXPANSION:          return "Barrier expand";
+      case PHASE_ADD_UNSAFE_BARRIER:         return "Add barrier to unsafe op";
       case PHASE_END:                        return "End";
       case PHASE_FAILURE:                    return "Failure";
       default:
--- a/src/hotspot/share/opto/vectornode.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/opto/vectornode.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -298,7 +298,6 @@
   case Op_LoadF:   case Op_LoadD:
   case Op_LoadP:   case Op_LoadN:
   case Op_LoadBarrierSlowReg:
-  case Op_LoadBarrierWeakSlowReg:
     *start = 0;
     *end   = 0; // no vector operands
     break;
--- a/src/hotspot/share/runtime/arguments.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/runtime/arguments.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -1630,8 +1630,8 @@
 #ifdef _LP64
   // MaxHeapSize is not set up properly at this point, but
   // the only value that can override MaxHeapSize if we are
-  // to use UseCompressedOops is InitialHeapSize.
-  size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
+  // to use UseCompressedOops are InitialHeapSize and MinHeapSize.
+  size_t max_heap_size = MAX3(MaxHeapSize, InitialHeapSize, MinHeapSize);
 
   if (max_heap_size <= max_heap_for_compressed_oops()) {
 #if !defined(COMPILER1) || defined(TIERED)
@@ -1832,6 +1832,8 @@
       // after call to limit_by_allocatable_memory because that
       // method might reduce the allocation size.
       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
+    } else if (!FLAG_IS_DEFAULT(MinHeapSize)) {
+      reasonable_max = MAX2(reasonable_max, (julong)MinHeapSize);
     }
 
     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
@@ -1855,13 +1857,13 @@
 
       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
 
-      log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
       FLAG_SET_ERGO(InitialHeapSize, (size_t)reasonable_initial);
+      log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, InitialHeapSize);
     }
-    // If the minimum heap size has not been set (via -Xms),
+    // If the minimum heap size has not been set (via -Xms or -XX:MinHeapSize),
     // synchronize with InitialHeapSize to avoid errors with the default value.
     if (MinHeapSize == 0) {
-      MinHeapSize = MIN2((size_t)reasonable_minimum, InitialHeapSize);
+      FLAG_SET_ERGO(MinHeapSize, MIN2((size_t)reasonable_minimum, InitialHeapSize));
       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, MinHeapSize);
     }
   }
@@ -1903,8 +1905,9 @@
     if (FLAG_SET_CMDLINE(InitialHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
       return JNI_EINVAL;
     }
-    // Currently the minimum size and the initial heap sizes are the same.
-    MinHeapSize = initHeapSize;
+    if (FLAG_SET_CMDLINE(MinHeapSize, initHeapSize) != JVMFlag::SUCCESS) {
+      return JNI_EINVAL;
+    }
   }
   if (FLAG_IS_DEFAULT(NewSize)) {
     // Make the young generation 3/8ths of the total heap.
@@ -2595,19 +2598,19 @@
       }
     // -Xms
     } else if (match_option(option, "-Xms", &tail)) {
-      julong long_initial_heap_size = 0;
+      julong size = 0;
       // an initial heap size of 0 means automatically determine
-      ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
+      ArgsRange errcode = parse_memory_size(tail, &size, 0);
       if (errcode != arg_in_range) {
         jio_fprintf(defaultStream::error_stream(),
                     "Invalid initial heap size: %s\n", option->optionString);
         describe_range_error(errcode);
         return JNI_EINVAL;
       }
-      MinHeapSize = (size_t)long_initial_heap_size;
-      // Currently the minimum size and the initial heap sizes are the same.
-      // Can be overridden with -XX:InitialHeapSize.
-      if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)long_initial_heap_size) != JVMFlag::SUCCESS) {
+      if (FLAG_SET_CMDLINE(MinHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
+        return JNI_EINVAL;
+      }
+      if (FLAG_SET_CMDLINE(InitialHeapSize, (size_t)size) != JVMFlag::SUCCESS) {
         return JNI_EINVAL;
       }
     // -Xmx
--- a/src/hotspot/share/runtime/java.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/runtime/java.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -310,7 +310,7 @@
   // CodeHeap State Analytics.
   // Does also call NMethodSweeper::print(tty)
   if (PrintCodeHeapAnalytics) {
-    CompileBroker::print_heapinfo(NULL, "all", "4096"); // details
+    CompileBroker::print_heapinfo(NULL, "all", 4096); // details
   } else if (PrintMethodFlushingStatistics) {
     NMethodSweeper::print(tty);
   }
@@ -378,7 +378,7 @@
   // CodeHeap State Analytics.
   // Does also call NMethodSweeper::print(tty)
   if (PrintCodeHeapAnalytics) {
-    CompileBroker::print_heapinfo(NULL, "all", "4096"); // details
+    CompileBroker::print_heapinfo(NULL, "all", 4096); // details
   } else if (PrintMethodFlushingStatistics) {
     NMethodSweeper::print(tty);
   }
--- a/src/hotspot/share/runtime/sharedRuntime.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/runtime/sharedRuntime.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -764,18 +764,9 @@
   throw_and_post_jvmti_exception(thread, exception);
 }
 
-#if INCLUDE_JVMCI
-address SharedRuntime::deoptimize_for_implicit_exception(JavaThread* thread, address pc, CompiledMethod* nm, int deopt_reason) {
-  assert(deopt_reason > Deoptimization::Reason_none && deopt_reason < Deoptimization::Reason_LIMIT, "invalid deopt reason");
-  thread->set_jvmci_implicit_exception_pc(pc);
-  thread->set_pending_deoptimization(Deoptimization::make_trap_request((Deoptimization::DeoptReason)deopt_reason, Deoptimization::Action_reinterpret));
-  return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
-}
-#endif // INCLUDE_JVMCI
-
 address SharedRuntime::continuation_for_implicit_exception(JavaThread* thread,
                                                            address pc,
-                                                           SharedRuntime::ImplicitExceptionKind exception_kind)
+                                                           ImplicitExceptionKind exception_kind)
 {
   address target_pc = NULL;
 
@@ -876,19 +867,7 @@
 #ifndef PRODUCT
           _implicit_null_throws++;
 #endif
-#if INCLUDE_JVMCI
-          if (cm->is_compiled_by_jvmci() && cm->pc_desc_at(pc) != NULL) {
-            // If there's no PcDesc then we'll die way down inside of
-            // deopt instead of just getting normal error reporting,
-            // so only go there if it will succeed.
-            return deoptimize_for_implicit_exception(thread, pc, cm, Deoptimization::Reason_null_check);
-          } else {
-#endif // INCLUDE_JVMCI
-          assert (cm->is_nmethod(), "Expect nmethod");
-          target_pc = ((nmethod*)cm)->continuation_for_implicit_exception(pc);
-#if INCLUDE_JVMCI
-          }
-#endif // INCLUDE_JVMCI
+          target_pc = cm->continuation_for_implicit_null_exception(pc);
           // If there's an unexpected fault, target_pc might be NULL,
           // in which case we want to fall through into the normal
           // error handling code.
@@ -904,15 +883,7 @@
 #ifndef PRODUCT
         _implicit_div0_throws++;
 #endif
-#if INCLUDE_JVMCI
-        if (cm->is_compiled_by_jvmci() && cm->pc_desc_at(pc) != NULL) {
-          return deoptimize_for_implicit_exception(thread, pc, cm, Deoptimization::Reason_div0_check);
-        } else {
-#endif // INCLUDE_JVMCI
-        target_pc = cm->continuation_for_implicit_exception(pc);
-#if INCLUDE_JVMCI
-        }
-#endif // INCLUDE_JVMCI
+        target_pc = cm->continuation_for_implicit_div0_exception(pc);
         // If there's an unexpected fault, target_pc might be NULL,
         // in which case we want to fall through into the normal
         // error handling code.
--- a/src/hotspot/share/runtime/sharedRuntime.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/runtime/sharedRuntime.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -204,9 +204,6 @@
   static address continuation_for_implicit_exception(JavaThread* thread,
                                                      address faulting_pc,
                                                      ImplicitExceptionKind exception_kind);
-#if INCLUDE_JVMCI
-  static address deoptimize_for_implicit_exception(JavaThread* thread, address pc, CompiledMethod* nm, int deopt_reason);
-#endif
 
   // Post-slow-path-allocation, pre-initializing-stores step for
   // implementing e.g. ReduceInitialCardMarks
--- a/src/hotspot/share/runtime/stackValue.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/runtime/stackValue.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -133,16 +133,12 @@
       }
 #endif
       // Deoptimization must make sure all oops have passed load barriers
-#if INCLUDE_ZGC
-      if (UseZGC) {
-        val = ZBarrier::load_barrier_on_oop_field_preloaded((oop*)value_addr, val);
-      }
-#endif
 #if INCLUDE_SHENANDOAHGC
       if (UseShenandoahGC) {
         val = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(val);
       }
 #endif
+      assert(oopDesc::is_oop_or_null(val, false), "bad oop found");
       Handle h(Thread::current(), val); // Wrap a handle around the oop
       return new StackValue(h);
     }
--- a/src/hotspot/share/services/diagnosticCommand.cpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/services/diagnosticCommand.cpp	Wed Jun 12 10:02:49 2019 +0530
@@ -946,13 +946,20 @@
 CodeHeapAnalyticsDCmd::CodeHeapAnalyticsDCmd(outputStream* output, bool heap) :
                                              DCmdWithParser(output, heap),
   _function("function", "Function to be performed (aggregate, UsedSpace, FreeSpace, MethodCount, MethodSpace, MethodAge, MethodNames, discard", "STRING", false, "all"),
-  _granularity("granularity", "Detail level - smaller value -> more detail", "STRING", false, "4096") {
+  _granularity("granularity", "Detail level - smaller value -> more detail", "INT", false, "4096") {
   _dcmdparser.add_dcmd_argument(&_function);
   _dcmdparser.add_dcmd_argument(&_granularity);
 }
 
 void CodeHeapAnalyticsDCmd::execute(DCmdSource source, TRAPS) {
-  CompileBroker::print_heapinfo(output(), _function.value(), _granularity.value());
+  jlong granularity = _granularity.value();
+  if (granularity < 1) {
+    Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IllegalArgumentException(),
+                       "Invalid granularity value " JLONG_FORMAT  ". Should be positive.\n", granularity);
+    return;
+  }
+
+  CompileBroker::print_heapinfo(output(), _function.value(), granularity);
 }
 
 int CodeHeapAnalyticsDCmd::num_arguments() {
--- a/src/hotspot/share/services/diagnosticCommand.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/services/diagnosticCommand.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -645,7 +645,7 @@
 class CodeHeapAnalyticsDCmd : public DCmdWithParser {
 protected:
   DCmdArgument<char*> _function;
-  DCmdArgument<char*> _granularity;
+  DCmdArgument<jlong> _granularity;
 public:
   CodeHeapAnalyticsDCmd(outputStream* output, bool heap);
   static const char* name() {
--- a/src/hotspot/share/utilities/growableArray.hpp	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/hotspot/share/utilities/growableArray.hpp	Wed Jun 12 10:02:49 2019 +0530
@@ -152,6 +152,12 @@
 template<class E> class GrowableArrayIterator;
 template<class E, class UnaryPredicate> class GrowableArrayFilterIterator;
 
+template<class E>
+class CompareClosure : public Closure {
+public:
+    virtual int do_compare(const E&, const E&) = 0;
+};
+
 template<class E> class GrowableArray : public GenericGrowableArray {
   friend class VMStructs;
 
@@ -443,6 +449,37 @@
     }
     return min;
   }
+
+  E insert_sorted(CompareClosure<E>* cc, const E& key) {
+    bool found;
+    int location = find_sorted(cc, key, found);
+    if (!found) {
+      insert_before(location, key);
+    }
+    return at(location);
+  }
+
+  template<typename K>
+  int find_sorted(CompareClosure<E>* cc, const K& key, bool& found) {
+    found = false;
+    int min = 0;
+    int max = length() - 1;
+
+    while (max >= min) {
+      int mid = (int)(((uint)max + min) / 2);
+      E value = at(mid);
+      int diff = cc->do_compare(key, value);
+      if (diff > 0) {
+        min = mid + 1;
+      } else if (diff < 0) {
+        max = mid - 1;
+      } else {
+        found = true;
+        return mid;
+      }
+    }
+    return min;
+  }
 };
 
 // Global GrowableArray methods (one instance in the library per each 'E' type).
--- a/src/java.base/share/classes/java/lang/Class.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/Class.java	Wed Jun 12 10:02:49 2019 +0530
@@ -917,7 +917,7 @@
      *
      * <p>If the superclass is a parameterized type, the {@code Type}
      * object returned must accurately reflect the actual type
-     * parameters used in the source code. The parameterized type
+     * arguments used in the source code. The parameterized type
      * representing the superclass is created if it had not been
      * created before. See the declaration of {@link
      * java.lang.reflect.ParameterizedType ParameterizedType} for the
@@ -1097,7 +1097,7 @@
      *
      * <p>If a superinterface is a parameterized type, the
      * {@code Type} object returned for it must accurately reflect
-     * the actual type parameters used in the source code. The
+     * the actual type arguments used in the source code. The
      * parameterized type representing each superinterface is created
      * if it had not been created before. See the declaration of
      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
--- a/src/java.base/share/classes/java/lang/Runtime.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/Runtime.java	Wed Jun 12 10:02:49 2019 +0530
@@ -684,32 +684,6 @@
     }
 
     /**
-     * Not implemented, does nothing.
-     *
-     * @deprecated
-     * This method was intended to control instruction tracing.
-     * It has been superseded by JVM-specific tracing mechanisms.
-     * This method is subject to removal in a future version of Java SE.
-     *
-     * @param on ignored
-     */
-    @Deprecated(since="9", forRemoval=true)
-    public void traceInstructions(boolean on) { }
-
-    /**
-     * Not implemented, does nothing.
-     *
-     * @deprecated
-     * This method was intended to control method call tracing.
-     * It has been superseded by JVM-specific tracing mechanisms.
-     * This method is subject to removal in a future version of Java SE.
-     *
-     * @param on ignored
-     */
-    @Deprecated(since="9", forRemoval=true)
-    public void traceMethodCalls(boolean on) { }
-
-    /**
      * Loads the native library specified by the filename argument.  The filename
      * argument must be an absolute path name.
      * (for example
--- a/src/java.base/share/classes/java/lang/reflect/Executable.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/reflect/Executable.java	Wed Jun 12 10:02:49 2019 +0530
@@ -234,6 +234,9 @@
      * parameter types, in declaration order, of the executable
      * represented by this object.  Returns an array of length
      * 0 if the underlying executable takes no parameters.
+     * Note that the constructors of some inner classes
+     * may have an implicitly declared parameter in addition to
+     * explicitly declared ones.
      *
      * @return the parameter types for the executable this object
      * represents
@@ -257,10 +260,13 @@
      * parameter types, in declaration order, of the executable represented by
      * this object. Returns an array of length 0 if the
      * underlying executable takes no parameters.
+     * Note that the constructors of some inner classes
+     * may have an implicitly declared parameter in addition to
+     * explicitly declared ones.
      *
      * <p>If a formal parameter type is a parameterized type,
      * the {@code Type} object returned for it must accurately reflect
-     * the actual type parameters used in the source code.
+     * the actual type arguments used in the source code.
      *
      * <p>If a formal parameter type is a type variable or a parameterized
      * type, it is created. Otherwise, it is resolved.
@@ -699,6 +705,9 @@
      *
      * Returns an array of length 0 if the method/constructor declares no
      * parameters.
+     * Note that the constructors of some inner classes
+     * may have an implicitly declared parameter in addition to
+     * explicitly declared ones.
      *
      * @return an array of objects representing the types of the
      * formal parameters of the method or constructor represented by this
--- a/src/java.base/share/classes/java/lang/reflect/Field.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/reflect/Field.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -243,9 +243,9 @@
      * Returns a {@code Type} object that represents the declared type for
      * the field represented by this {@code Field} object.
      *
-     * <p>If the {@code Type} is a parameterized type, the
-     * {@code Type} object returned must accurately reflect the
-     * actual type parameters used in the source code.
+     * <p>If the declared type of the field is a parameterized type,
+     * the {@code Type} object returned must accurately reflect the
+     * actual type arguments used in the source code.
      *
      * <p>If the type of the underlying field is a type variable or a
      * parameterized type, it is created. Otherwise, it is resolved.
--- a/src/java.base/share/classes/java/lang/reflect/Method.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/reflect/Method.java	Wed Jun 12 10:02:49 2019 +0530
@@ -269,7 +269,7 @@
      *
      * <p>If the return type is a parameterized type,
      * the {@code Type} object returned must accurately reflect
-     * the actual type parameters used in the source code.
+     * the actual type arguments used in the source code.
      *
      * <p>If the return type is a type variable or a parameterized type, it
      * is created. Otherwise, it is resolved.
--- a/src/java.base/share/classes/java/lang/reflect/TypeVariable.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/lang/reflect/TypeVariable.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,7 +72,7 @@
 
     /**
      * Returns the {@code GenericDeclaration} object representing the
-     * generic declaration declared this type variable.
+     * generic declaration declared for this type variable.
      *
      * @return the generic declaration declared for this type variable.
      *
--- a/src/java.base/share/classes/java/net/ServerSocket.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/net/ServerSocket.java	Wed Jun 12 10:02:49 2019 +0530
@@ -106,9 +106,10 @@
      * request to connect) is set to {@code 50}. If a connection
      * indication arrives when the queue is full, the connection is refused.
      * <p>
-     * If the application has specified a server socket factory, that
-     * factory's {@code createSocketImpl} method is called to create
-     * the actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a server socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      * <p>
      * If there is a security manager,
      * its {@code checkListen} method is called
@@ -150,9 +151,10 @@
      * a connection indication arrives when the queue is full, the
      * connection is refused.
      * <p>
-     * If the application has specified a server socket factory, that
-     * factory's {@code createSocketImpl} method is called to create
-     * the actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a server socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      * <p>
      * If there is a security manager,
      * its {@code checkListen} method is called
--- a/src/java.base/share/classes/java/net/Socket.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/java/net/Socket.java	Wed Jun 12 10:02:49 2019 +0530
@@ -89,8 +89,12 @@
     }
 
     /**
-     * Creates an unconnected socket, with the
-     * system-default type of SocketImpl.
+     * Creates an unconnected Socket.
+     * <p>
+     * If the application has specified a client socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      *
      * @since   1.1
      * @revised 1.4
@@ -194,9 +198,10 @@
      * In other words, it is equivalent to specifying an address of the
      * loopback interface. </p>
      * <p>
-     * If the application has specified a server socket factory, that
-     * factory's {@code createSocketImpl} method is called to create
-     * the actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a client socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      * <p>
      * If there is a security manager, its
      * {@code checkConnect} method is called
@@ -232,9 +237,10 @@
      * Creates a stream socket and connects it to the specified port
      * number at the specified IP address.
      * <p>
-     * If the application has specified a socket factory, that factory's
-     * {@code createSocketImpl} method is called to create the
-     * actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a client socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      * <p>
      * If there is a security manager, its
      * {@code checkConnect} method is called
@@ -358,9 +364,10 @@
      * stream socket. If the stream argument is {@code false}, it
      * creates a datagram socket.
      * <p>
-     * If the application has specified a server socket factory, that
-     * factory's {@code createSocketImpl} method is called to create
-     * the actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a client socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      * <p>
      * If there is a security manager, its
      * {@code checkConnect} method is called
@@ -400,9 +407,10 @@
      * stream socket. If the stream argument is {@code false}, it
      * creates a datagram socket.
      * <p>
-     * If the application has specified a server socket factory, that
-     * factory's {@code createSocketImpl} method is called to create
-     * the actual socket implementation. Otherwise a "plain" socket is created.
+     * If the application has specified a client socket implementation
+     * factory, that factory's {@code createSocketImpl} method is called to
+     * create the actual socket implementation. Otherwise a system-default
+     * socket implementation is created.
      *
      * <p>If there is a security manager, its
      * {@code checkConnect} method is called
--- a/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,8 +55,15 @@
     private void validateConstructorArguments() {
         TypeVariable<?>[] formals = rawType.getTypeParameters();
         // check correct arity of actual type args
-        if (formals.length != actualTypeArguments.length){
-            throw new MalformedParameterizedTypeException();
+        if (formals.length != actualTypeArguments.length) {
+            throw new MalformedParameterizedTypeException(String.format("Mismatch of count of " +
+                                                                        "formal and actual type " +
+                                                                        "arguments in constructor " +
+                                                                        "of %s: %d formal argument(s) "+
+                                                                        "%d actual argument(s)",
+                                                                        rawType.getName(),
+                                                                        formals.length,
+                                                                        actualTypeArguments.length));
         }
         for (int i = 0; i < actualTypeArguments.length; i++) {
             // check actuals against formals' bounds
--- a/src/java.base/share/classes/sun/security/ssl/ClientHello.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/ClientHello.java	Wed Jun 12 10:02:49 2019 +0530
@@ -35,7 +35,6 @@
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
-import java.util.Objects;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.SSLPeerUnverifiedException;
@@ -969,11 +968,24 @@
                 }
             }
 
-            // Is it an abbreviated handshake?
-            if (clientHello.sessionId.length() != 0) {
-                SSLSessionImpl previous = ((SSLSessionContextImpl)shc.sslContext
-                            .engineGetServerSessionContext())
-                            .get(clientHello.sessionId.getId());
+            // Consume a Session Ticket Extension if it exists
+            SSLExtension[] ext = new SSLExtension[]{
+                    SSLExtension.CH_SESSION_TICKET
+            };
+            clientHello.extensions.consumeOnLoad(shc, ext);
+
+            // Does the client want to resume a session?
+            if (clientHello.sessionId.length() != 0 || shc.statelessResumption) {
+                SSLSessionContextImpl cache = (SSLSessionContextImpl)shc.sslContext
+                        .engineGetServerSessionContext();
+
+                SSLSessionImpl previous;
+                // Use the stateless session ticket if provided
+                if (shc.statelessResumption) {
+                    previous = shc.resumingSession;
+                } else {
+                    previous = cache.get(clientHello.sessionId.getId());
+                }
 
                 boolean resumingSession =
                         (previous != null) && previous.isRejoinable();
@@ -1051,14 +1063,20 @@
                 // the resuming options later.
                 shc.isResumption = resumingSession;
                 shc.resumingSession = resumingSession ? previous : null;
+
+                if (!resumingSession && SSLLogger.isOn &&
+                        SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Session not resumed.");
+                }
             }
 
             // cache the client random number for further using
             shc.clientHelloRandom = clientHello.clientRandom;
 
             // Check and launch ClientHello extensions.
-            SSLExtension[] extTypes = shc.sslConfig.getEnabledExtensions(
-                    SSLHandshake.CLIENT_HELLO);
+            SSLExtension[] extTypes = shc.sslConfig.getExclusiveExtensions(
+                    SSLHandshake.CLIENT_HELLO,
+                    Arrays.asList(SSLExtension.CH_SESSION_TICKET));
             clientHello.extensions.consumeOnLoad(shc, extTypes);
 
             //
@@ -1276,11 +1294,25 @@
                 }
             }
 
-            // Is it an abbreviated handshake?
+
+            // Does the client want to resume a session?
             if (clientHello.sessionId.length() != 0) {
-                SSLSessionImpl previous = ((SSLSessionContextImpl)shc.sslContext
-                            .engineGetServerSessionContext())
-                            .get(clientHello.sessionId.getId());
+                SSLSessionContextImpl cache = (SSLSessionContextImpl)shc.sslContext
+                        .engineGetServerSessionContext();
+
+                // Consume a Session Ticket Extension if it exists
+                SSLExtension[] ext = new SSLExtension[]{
+                        SSLExtension.CH_SESSION_TICKET
+                };
+                clientHello.extensions.consumeOnLoad(shc, ext);
+
+                SSLSessionImpl previous;
+                // Use stateless session ticket if provided.
+                if (shc.statelessResumption) {
+                    previous = shc.resumingSession;
+                } else {
+                    previous = cache.get(clientHello.sessionId.getId());
+                }
 
                 boolean resumingSession =
                         (previous != null) && previous.isRejoinable();
--- a/src/java.base/share/classes/sun/security/ssl/Finished.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/Finished.java	Wed Jun 12 10:02:49 2019 +0530
@@ -410,6 +410,10 @@
                 chc.conContext.clientVerifyData = fm.verifyData;
             }
 
+            if (chc.statelessResumption) {
+                chc.handshakeConsumers.put(
+                        SSLHandshake.NEW_SESSION_TICKET.id, SSLHandshake.NEW_SESSION_TICKET);
+            }
             // update the consumers and producers
             if (!chc.isResumption) {
                 chc.conContext.consumers.put(ContentType.CHANGE_CIPHER_SPEC.id,
@@ -441,6 +445,10 @@
 
         private byte[] onProduceFinished(ServerHandshakeContext shc,
                 HandshakeMessage message) throws IOException {
+            if (shc.statelessResumption) {
+                NewSessionTicket.handshake12Producer.produce(shc, message);
+            }
+
             // Refresh handshake hash
             shc.handshakeHash.update();
 
@@ -473,7 +481,8 @@
                         SSLHandshake.FINISHED.id, SSLHandshake.FINISHED);
                 shc.conContext.inputRecord.expectingFinishFlight();
             } else {
-                if (shc.handshakeSession.isRejoinable()) {
+                if (shc.handshakeSession.isRejoinable() &&
+                        !shc.statelessResumption) {
                     ((SSLSessionContextImpl)shc.sslContext.
                         engineGetServerSessionContext()).put(
                             shc.handshakeSession);
@@ -591,7 +600,8 @@
             }
 
             if (shc.isResumption) {
-                if (shc.handshakeSession.isRejoinable()) {
+                if (shc.handshakeSession.isRejoinable() &&
+                        !shc.statelessResumption) {
                     ((SSLSessionContextImpl)shc.sslContext.
                         engineGetServerSessionContext()).put(
                             shc.handshakeSession);
@@ -915,9 +925,9 @@
 
             // save the session
             if (!chc.isResumption && chc.handshakeSession.isRejoinable()) {
-                SSLSessionContextImpl sessionContext = (SSLSessionContextImpl)
-                chc.sslContext.engineGetClientSessionContext();
-                sessionContext.put(chc.handshakeSession);
+                ((SSLSessionContextImpl)chc.sslContext.
+                        engineGetClientSessionContext()).
+                        put(chc.handshakeSession);
             }
 
             // derive salt secret
@@ -1028,10 +1038,11 @@
                         shc.negotiatedProtocol);
             }
 
-            // save the session
-            if (!shc.isResumption && shc.handshakeSession.isRejoinable()) {
+            // Save the session if possible and not stateless
+            if (!shc.statelessResumption && !shc.isResumption &&
+                    shc.handshakeSession.isRejoinable()) {
                 SSLSessionContextImpl sessionContext = (SSLSessionContextImpl)
-                shc.sslContext.engineGetServerSessionContext();
+                        shc.sslContext.engineGetServerSessionContext();
                 sessionContext.put(shc.handshakeSession);
             }
 
--- a/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java	Wed Jun 12 10:02:49 2019 +0530
@@ -102,6 +102,8 @@
     // Resumption
     boolean                                 isResumption;
     SSLSessionImpl                          resumingSession;
+    // Session is using stateless resumption
+    boolean                                 statelessResumption = false;
 
     final Queue<Map.Entry<Byte, ByteBuffer>> delegatedActions;
     volatile boolean                        taskDelegated = false;
@@ -551,7 +553,7 @@
 
     List<SNIServerName> getRequestedServerNames() {
         if (requestedServerNames == null) {
-            return Collections.<SNIServerName>emptyList();
+            return Collections.emptyList();
         }
         return requestedServerNames;
     }
--- a/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java	Wed Jun 12 10:02:49 2019 +0530
@@ -28,40 +28,139 @@
 import java.math.BigInteger;
 import java.nio.ByteBuffer;
 import java.security.GeneralSecurityException;
-import java.security.ProviderException;
 import java.security.SecureRandom;
 import java.text.MessageFormat;
 import java.util.Locale;
 import javax.crypto.SecretKey;
 import javax.net.ssl.SSLHandshakeException;
 import sun.security.ssl.PskKeyExchangeModesExtension.PskKeyExchangeModesSpec;
+import sun.security.ssl.SessionTicketExtension.SessionTicketSpec;
+import sun.security.ssl.SSLHandshake.HandshakeMessage;
+import sun.security.util.HexDumpEncoder;
 
-import sun.security.ssl.SSLHandshake.HandshakeMessage;
+import static sun.security.ssl.SSLHandshake.NEW_SESSION_TICKET;
 
 /**
  * Pack of the NewSessionTicket handshake message.
  */
 final class NewSessionTicket {
-    private static final int MAX_TICKET_LIFETIME = 604800;  // seconds, 7 days
+    static final int MAX_TICKET_LIFETIME = 604800;  // seconds, 7 days
 
     static final SSLConsumer handshakeConsumer =
-        new NewSessionTicketConsumer();
+        new T13NewSessionTicketConsumer();
+    static final SSLConsumer handshake12Consumer =
+        new T12NewSessionTicketConsumer();
     static final SSLProducer kickstartProducer =
         new NewSessionTicketKickstartProducer();
-    static final HandshakeProducer handshakeProducer =
-        new NewSessionTicketProducer();
+    static final HandshakeProducer handshake12Producer =
+        new T12NewSessionTicketProducer();
 
     /**
-     * The NewSessionTicketMessage handshake message.
+     * The NewSessionTicketMessage handshake messages.
+     */
+    abstract static class NewSessionTicketMessage extends HandshakeMessage {
+        int ticketLifetime;
+        byte[] ticket;
+
+        NewSessionTicketMessage(HandshakeContext context) {
+            super(context);
+        }
+
+        @Override
+        public SSLHandshake handshakeType() {
+            return NEW_SESSION_TICKET;
+        }
+
+        // For TLS 1.3 only
+        int getTicketAgeAdd() throws IOException {
+            throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER,
+                    "TicketAgeAdd not part of RFC 5077.");
+        }
+
+        // For TLS 1.3 only
+        byte[] getTicketNonce() throws IOException {
+            throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER,
+                    "TicketNonce not part of RFC 5077.");
+        }
+
+    }
+    /**
+     * NewSessionTicket for TLS 1.2 and below (RFC 5077)
      */
-    static final class NewSessionTicketMessage extends HandshakeMessage {
-        final int ticketLifetime;
-        final int ticketAgeAdd;
-        final byte[] ticketNonce;
-        final byte[] ticket;
-        final SSLExtensions extensions;
+    static final class T12NewSessionTicketMessage extends NewSessionTicketMessage {
+
+        T12NewSessionTicketMessage(HandshakeContext context,
+                int ticketLifetime, byte[] ticket) {
+            super(context);
+
+            this.ticketLifetime = ticketLifetime;
+            this.ticket = ticket;
+        }
+
+        T12NewSessionTicketMessage(HandshakeContext context,
+                ByteBuffer m) throws IOException {
+
+            // RFC5077 struct {
+            //     uint32 ticket_lifetime;
+            //     opaque ticket<1..2^16-1>;
+            // } NewSessionTicket;
+
+            super(context);
+            if (m.remaining() < 14) {
+                throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER,
+                        "Invalid NewSessionTicket message: no sufficient data");
+            }
+
+            this.ticketLifetime = Record.getInt32(m);
+            this.ticket = Record.getBytes16(m);
+        }
+
+        @Override
+        public SSLHandshake handshakeType() {
+            return NEW_SESSION_TICKET;
+        }
 
-        NewSessionTicketMessage(HandshakeContext context,
+        @Override
+        public int messageLength() {
+            return 4 + // ticketLifetime
+                    2 + ticket.length;  // len of ticket + ticket
+        }
+
+        @Override
+        public void send(HandshakeOutStream hos) throws IOException {
+            hos.putInt32(ticketLifetime);
+            hos.putBytes16(ticket);
+        }
+
+        @Override
+        public String toString() {
+            MessageFormat messageFormat = new MessageFormat(
+                    "\"NewSessionTicket\": '{'\n" +
+                            "  \"ticket_lifetime\"      : \"{0}\",\n" +
+                            "  \"ticket\"               : '{'\n" +
+                            "{1}\n" +
+                            "  '}'" +
+                            "'}'",
+                Locale.ENGLISH);
+
+            HexDumpEncoder hexEncoder = new HexDumpEncoder();
+            Object[] messageFields = {
+                    ticketLifetime,
+                    Utilities.indent(hexEncoder.encode(ticket), "    "),
+            };
+            return messageFormat.format(messageFields);
+        }
+    }
+
+    /**
+     * NewSessionTicket defined by the TLS 1.3
+     */
+    static final class T13NewSessionTicketMessage extends NewSessionTicketMessage {
+        int ticketAgeAdd;
+        byte[] ticketNonce;
+        SSLExtensions extensions;
+
+        T13NewSessionTicketMessage(HandshakeContext context,
                 int ticketLifetime, SecureRandom generator,
                 byte[] ticketNonce, byte[] ticket) {
             super(context);
@@ -73,7 +172,7 @@
             this.extensions = new SSLExtensions(this);
         }
 
-        NewSessionTicketMessage(HandshakeContext context,
+        T13NewSessionTicketMessage(HandshakeContext context,
                 ByteBuffer m) throws IOException {
             super(context);
 
@@ -84,6 +183,7 @@
             //     opaque ticket<1..2^16-1>;
             //     Extension extensions<0..2^16-2>;
             // } NewSessionTicket;
+
             if (m.remaining() < 14) {
                 throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER,
                     "Invalid NewSessionTicket message: no sufficient data");
@@ -111,24 +211,36 @@
 
             SSLExtension[] supportedExtensions =
                     context.sslConfig.getEnabledExtensions(
-                            SSLHandshake.NEW_SESSION_TICKET);
+                            NEW_SESSION_TICKET);
             this.extensions = new SSLExtensions(this, m, supportedExtensions);
         }
 
         @Override
         public SSLHandshake handshakeType() {
-            return SSLHandshake.NEW_SESSION_TICKET;
+            return NEW_SESSION_TICKET;
+        }
+
+        int getTicketAgeAdd() {
+            return ticketAgeAdd;
+        }
+
+        byte[] getTicketNonce() {
+            return ticketNonce;
         }
 
         @Override
         public int messageLength() {
+
             int extLen = extensions.length();
             if (extLen == 0) {
                 extLen = 2;     // empty extensions
             }
 
-            return 8 + ticketNonce.length + 1 +
-                       ticket.length + 2 + extLen;
+            return 4 +// ticketLifetime
+                    4 + // ticketAgeAdd
+                    1 + ticketNonce.length + // len of nonce + nonce
+                    2 + ticket.length + // len of ticket + ticket
+                    extLen;
         }
 
         @Override
@@ -153,18 +265,21 @@
                 "  \"ticket_lifetime\"      : \"{0}\",\n" +
                 "  \"ticket_age_add\"       : \"{1}\",\n" +
                 "  \"ticket_nonce\"         : \"{2}\",\n" +
-                "  \"ticket\"               : \"{3}\",\n" +
+                "  \"ticket\"               : '{'\n" +
+                "{3}\n" +
+                "  '}'" +
                 "  \"extensions\"           : [\n" +
                 "{4}\n" +
                 "  ]\n" +
                 "'}'",
                 Locale.ENGLISH);
 
+            HexDumpEncoder hexEncoder = new HexDumpEncoder();
             Object[] messageFields = {
                 ticketLifetime,
                 "<omitted>",    //ticketAgeAdd should not be logged
                 Utilities.toHexString(ticketNonce),
-                Utilities.toHexString(ticket),
+                Utilities.indent(hexEncoder.encode(ticket), "    "),
                 Utilities.indent(extensions.toString(), "    ")
             };
 
@@ -248,25 +363,46 @@
                 }
                 return null;
             }
-            NewSessionTicketMessage nstm = new NewSessionTicketMessage(shc,
-                sessionTimeoutSeconds, shc.sslContext.getSecureRandom(),
-                nonceArr, newId.getId());
-            if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
-                SSLLogger.fine(
-                        "Produced NewSessionTicket handshake message", nstm);
-            }
 
-            // create and cache the new session
-            // The new session must be a child of the existing session so
-            // they will be invalidated together, etc.
+            NewSessionTicketMessage nstm;
+
             SSLSessionImpl sessionCopy =
                     new SSLSessionImpl(shc.handshakeSession, newId);
-            shc.handshakeSession.addChild(sessionCopy);
             sessionCopy.setPreSharedKey(psk);
             sessionCopy.setPskIdentity(newId.getId());
-            sessionCopy.setTicketAgeAdd(nstm.ticketAgeAdd);
-            sessionCache.put(sessionCopy);
 
+            if (shc.statelessResumption) {
+                try {
+                    nstm = new T13NewSessionTicketMessage(shc,
+                            sessionTimeoutSeconds, shc.sslContext.getSecureRandom(),
+                            nonceArr, new SessionTicketSpec().encrypt(shc, sessionCopy));
+                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                        SSLLogger.fine(
+                                "Produced NewSessionTicket stateless " +
+                                        "handshake message", nstm);
+                    }
+                } catch (Exception e) {
+                    // Error with NST ticket, abort NST
+                    shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, e);
+                    return null;
+                }
+            } else {
+                nstm = new T13NewSessionTicketMessage(shc, sessionTimeoutSeconds,
+                        shc.sslContext.getSecureRandom(), nonceArr,
+                        newId.getId());
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine(
+                            "Produced NewSessionTicket handshake message",
+                            nstm);
+                }
+
+                // create and cache the new session
+                // The new session must be a child of the existing session so
+                // they will be invalidated together, etc.
+                shc.handshakeSession.addChild(sessionCopy);
+                sessionCopy.setTicketAgeAdd(nstm.getTicketAgeAdd());
+                sessionCache.put(sessionCopy);
+            }
             // Output the handshake message.
             nstm.write(shc.handshakeOutput);
             shc.handshakeOutput.flush();
@@ -277,13 +413,13 @@
     }
 
     /**
-     * The "NewSessionTicket" handshake message producer.
+     * The "NewSessionTicket" handshake message producer for RFC 5077
      */
-    private static final class NewSessionTicketProducer
+    private static final class T12NewSessionTicketProducer
             implements HandshakeProducer {
 
         // Prevent instantiation of this class.
-        private NewSessionTicketProducer() {
+        private T12NewSessionTicketProducer() {
             // blank
         }
 
@@ -291,24 +427,65 @@
         public byte[] produce(ConnectionContext context,
                 HandshakeMessage message) throws IOException {
 
-            // NSTM may be sent in response to handshake messages.
-            // For example: key update
+            ServerHandshakeContext shc = (ServerHandshakeContext)context;
+
+            // Is this session resumable?
+            if (!shc.handshakeSession.isRejoinable()) {
+                return null;
+            }
+
+            // get a new session ID
+            SessionId newId = shc.handshakeSession.getSessionId();
+
+            SSLSessionContextImpl sessionCache = (SSLSessionContextImpl)
+                    shc.sslContext.engineGetServerSessionContext();
+            int sessionTimeoutSeconds = sessionCache.getSessionTimeout();
+            if (sessionTimeoutSeconds > MAX_TICKET_LIFETIME) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine(
+                        "Session timeout is too long. No ticket sent.");
+                }
+                return null;
+            }
+
+            NewSessionTicketMessage nstm;
 
-            throw new ProviderException(
-                "NewSessionTicket handshake producer not implemented");
+            SSLSessionImpl sessionCopy =
+                    new SSLSessionImpl(shc.handshakeSession, newId);
+            sessionCopy.setPskIdentity(newId.getId());
+
+            try {
+                nstm = new T12NewSessionTicketMessage(shc, sessionTimeoutSeconds,
+                        new SessionTicketSpec().encrypt(shc, sessionCopy));
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine(
+                            "Produced NewSessionTicket stateless handshake message", nstm);
+                }
+            } catch (Exception e) {
+                // Abort on error with NST ticket
+                shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, e);
+                return null;
+            }
+
+            // Output the handshake message.
+            nstm.write(shc.handshakeOutput);
+            shc.handshakeOutput.flush();
+
+            // The message has been delivered.
+            return null;
         }
     }
 
     private static final
-            class NewSessionTicketConsumer implements SSLConsumer {
+    class T13NewSessionTicketConsumer implements SSLConsumer {
         // Prevent instantiation of this class.
-        private NewSessionTicketConsumer() {
+        private T13NewSessionTicketConsumer() {
             // blank
         }
 
         @Override
         public void consume(ConnectionContext context,
-                            ByteBuffer message) throws IOException {
+                ByteBuffer message) throws IOException {
 
             // Note: Although the resumption master secret depends on the
             // client's second flight, servers which do not request client
@@ -317,13 +494,12 @@
             // upon sending its Finished rather than waiting for the client
             // Finished.
             //
-            // The consuming happens in client side only.  As the server
-            // may send the NewSessionTicket before handshake complete, the
-            // context may be a PostHandshakeContext or HandshakeContext
-            // instance.
+            // The consuming happens in client side only and is received after
+            // the server's Finished message with PostHandshakeContext.
+
             HandshakeContext hc = (HandshakeContext)context;
             NewSessionTicketMessage nstm =
-                    new NewSessionTicketMessage(hc, message);
+                    new T13NewSessionTicketMessage(hc, message);
             if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                 SSLLogger.fine(
                 "Consuming NewSessionTicket message", nstm);
@@ -352,37 +528,95 @@
             }
 
             SSLSessionImpl sessionToSave = hc.conContext.conSession;
-
-            SecretKey resumptionMasterSecret =
-                sessionToSave.getResumptionMasterSecret();
-            if (resumptionMasterSecret == null) {
-                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
-                    SSLLogger.fine(
-                    "Session has no resumption master secret. Ignoring ticket.");
+            SecretKey psk = null;
+            if (hc.negotiatedProtocol.useTLS13PlusSpec()) {
+                SecretKey resumptionMasterSecret =
+                        sessionToSave.getResumptionMasterSecret();
+                if (resumptionMasterSecret == null) {
+                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                        SSLLogger.fine(
+                                "Session has no resumption master secret." +
+                                        " Ignoring ticket.");
+                    }
+                    return;
                 }
-                return;
+
+                // derive the PSK
+                psk = derivePreSharedKey(
+                        sessionToSave.getSuite().hashAlg,
+                        resumptionMasterSecret, nstm.getTicketNonce());
             }
 
-            // derive the PSK
-            SecretKey psk = derivePreSharedKey(
-                sessionToSave.getSuite().hashAlg, resumptionMasterSecret,
-                nstm.ticketNonce);
-
             // create and cache the new session
             // The new session must be a child of the existing session so
             // they will be invalidated together, etc.
             SessionId newId =
-                new SessionId(true, hc.sslContext.getSecureRandom());
+                    new SessionId(true, hc.sslContext.getSecureRandom());
             SSLSessionImpl sessionCopy = new SSLSessionImpl(sessionToSave,
                     newId);
             sessionToSave.addChild(sessionCopy);
             sessionCopy.setPreSharedKey(psk);
-            sessionCopy.setTicketAgeAdd(nstm.ticketAgeAdd);
+            sessionCopy.setTicketAgeAdd(nstm.getTicketAgeAdd());
             sessionCopy.setPskIdentity(nstm.ticket);
             sessionCache.put(sessionCopy);
 
             // clean handshake context
-            hc.conContext.finishPostHandshake();
+            if (hc.negotiatedProtocol.useTLS13PlusSpec()) {
+                hc.conContext.finishPostHandshake();
+            }
+        }
+    }
+
+    private static final
+    class T12NewSessionTicketConsumer implements SSLConsumer {
+        // Prevent instantiation of this class.
+        private T12NewSessionTicketConsumer() {
+            // blank
+        }
+
+        @Override
+        public void consume(ConnectionContext context,
+                ByteBuffer message) throws IOException {
+
+            HandshakeContext hc = (HandshakeContext)context;
+            hc.handshakeConsumers.remove(NEW_SESSION_TICKET.id);
+
+            NewSessionTicketMessage nstm = new T12NewSessionTicketMessage(hc,
+                    message);
+            if (nstm.ticket.length == 0) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("NewSessionTicket ticket was empty");
+                }
+                return;
+            }
+
+            // discard tickets with timeout 0
+            if (nstm.ticketLifetime <= 0 ||
+                nstm.ticketLifetime > MAX_TICKET_LIFETIME) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine(
+                    "Discarding NewSessionTicket with lifetime "
+                        + nstm.ticketLifetime, nstm);
+                }
+                return;
+            }
+
+            SSLSessionContextImpl sessionCache = (SSLSessionContextImpl)
+                    hc.sslContext.engineGetClientSessionContext();
+
+            if (sessionCache.getSessionTimeout() > MAX_TICKET_LIFETIME) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine(
+                    "Session cache lifetime is too long. Discarding ticket.");
+                }
+                return;
+            }
+
+            hc.handshakeSession.setPskIdentity(nstm.ticket);
+            if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                SSLLogger.fine("Consuming NewSessionTicket\n" +
+                        nstm.toString());
+            }
         }
     }
 }
--- a/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java	Wed Jun 12 10:02:49 2019 +0530
@@ -32,7 +32,6 @@
 import java.util.ArrayList;
 import java.util.Locale;
 import java.util.Arrays;
-import java.util.Objects;
 import java.util.Collection;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
@@ -42,6 +41,9 @@
 import sun.security.ssl.SSLExtension.ExtensionConsumer;
 import sun.security.ssl.SSLExtension.SSLExtensionSpec;
 import sun.security.ssl.SSLHandshake.HandshakeMessage;
+import sun.security.ssl.SessionTicketExtension.SessionTicketSpec;
+import sun.security.util.HexDumpEncoder;
+
 import static sun.security.ssl.SSLExtension.*;
 
 /**
@@ -88,7 +90,7 @@
 
         @Override
         public String toString() {
-            return "{" + Utilities.toHexString(identity) + "," +
+            return "{" + Utilities.toHexString(identity) + ", " +
                 obfuscatedAge + "}";
         }
     }
@@ -208,8 +210,10 @@
         public String toString() {
             MessageFormat messageFormat = new MessageFormat(
                 "\"PreSharedKey\": '{'\n" +
-                "  \"identities\"    : \"{0}\",\n" +
-                "  \"binders\"       : \"{1}\",\n" +
+                "  \"identities\": '{'\n" +
+                "{0}\n" +
+                "  '}'" +
+                "  \"binders\": \"{1}\",\n" +
                 "'}'",
                 Locale.ENGLISH);
 
@@ -222,9 +226,13 @@
         }
 
         String identitiesString() {
+            HexDumpEncoder hexEncoder = new HexDumpEncoder();
+
             StringBuilder result = new StringBuilder();
             for (PskIdentity curId : identities) {
-                result.append(curId.toString() + "\n");
+                result.append("  {\n"+ Utilities.indent(
+                        hexEncoder.encode(curId.identity), "    ") +
+                        "\n  }\n");
             }
 
             return result.toString();
@@ -278,7 +286,7 @@
             this.selectedIdentity = Record.getInt16(m);
         }
 
-        byte[] getEncoded() throws IOException {
+        byte[] getEncoded() {
             return new byte[] {
                 (byte)((selectedIdentity >> 8) & 0xFF),
                 (byte)(selectedIdentity & 0xFF)
@@ -368,8 +376,36 @@
                 SSLSessionContextImpl sessionCache = (SSLSessionContextImpl)
                         shc.sslContext.engineGetServerSessionContext();
                 int idIndex = 0;
+                SSLSessionImpl s = null;
+
                 for (PskIdentity requestedId : pskSpec.identities) {
-                    SSLSessionImpl s = sessionCache.get(requestedId.identity);
+                    // If we are keeping state, see if the identity is in the cache
+                    if (requestedId.identity.length == SessionId.MAX_LENGTH) {
+                        s = sessionCache.get(requestedId.identity);
+                    }
+                    // See if the identity is a stateless ticket
+                    if (s == null &&
+                            requestedId.identity.length > SessionId.MAX_LENGTH &&
+                            sessionCache.statelessEnabled()) {
+                        ByteBuffer b =
+                                new SessionTicketSpec(requestedId.identity).
+                                        decrypt(shc);
+                        if (b != null) {
+                            try {
+                                s = new SSLSessionImpl(shc, b);
+                            } catch (IOException | RuntimeException e) {
+                                s = null;
+                            }
+                        }
+                        if (b == null || s == null) {
+                            if (SSLLogger.isOn &&
+                                    SSLLogger.isOn("ssl,handshake")) {
+                                SSLLogger.fine(
+                                        "Stateless session ticket invalid");
+                            }
+                        }
+                    }
+
                     if (s != null && canRejoin(clientHello, shc, s)) {
                         if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
                             SSLLogger.fine("Resuming session: ", s);
@@ -391,7 +427,6 @@
                     shc.resumingSession = null;
                 }
             }
-
             // update the context
             shc.handshakeExtensions.put(
                 SSLExtension.CH_PRE_SHARED_KEY, pskSpec);
@@ -708,7 +743,8 @@
                 int hashLength, List<PskIdentity> identities) {
             List<byte[]> binders = new ArrayList<>();
             byte[] binderProto = new byte[hashLength];
-            for (PskIdentity curId : identities) {
+            int i = identities.size();
+            while (i-- > 0) {
                 binders.add(binderProto);
             }
 
--- a/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Wed Jun 12 10:02:49 2019 +0530
@@ -71,11 +71,13 @@
     private volatile StatusResponseManager statusResponseManager;
 
     private final ReentrantLock contextLock = new ReentrantLock();
+    final HashMap<Integer, SessionTicketExtension.StatelessKey> keyHashMap = new HashMap<>();
+
 
     SSLContextImpl() {
         ephemeralKeyManager = new EphemeralKeyManager();
-        clientCache = new SSLSessionContextImpl();
-        serverCache = new SSLSessionContextImpl();
+        clientCache = new SSLSessionContextImpl(false);
+        serverCache = new SSLSessionContextImpl(true);
     }
 
     @Override
--- a/src/java.base/share/classes/sun/security/ssl/SSLExtension.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLExtension.java	Wed Jun 12 10:02:49 2019 +0530
@@ -309,8 +309,28 @@
     // extensions defined in RFC 7924
     CACHED_INFO             (0x0019, "cached_info"),
 
-    // extensions defined in RFC 4507/5077
-    SESSION_TICKET          (0x0023, "session_ticket"),
+    // extensions defined in RFC 5077
+    CH_SESSION_TICKET       (0x0023, "session_ticket",
+            SSLHandshake.CLIENT_HELLO,
+            ProtocolVersion.PROTOCOLS_10_12,
+            SessionTicketExtension.chNetworkProducer,
+            SessionTicketExtension.chOnLoadConsumer,
+            null,
+            null,
+            null,
+            SessionTicketExtension.steStringizer),
+            //null),
+
+    SH_SESSION_TICKET       (0x0023, "session_ticket",
+            SSLHandshake.SERVER_HELLO,
+            ProtocolVersion.PROTOCOLS_10_12,
+            SessionTicketExtension.shNetworkProducer,
+            SessionTicketExtension.shOnLoadConsumer,
+            null,
+            null,
+            null,
+            SessionTicketExtension.steStringizer),
+            //null),
 
     // extensions defined in TLS 1.3
     CH_EARLY_DATA           (0x002A, "early_data"),
--- a/src/java.base/share/classes/sun/security/ssl/SSLHandshake.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLHandshake.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -115,15 +115,19 @@
     NEW_SESSION_TICKET          ((byte)0x04, "new_session_ticket",
         (Map.Entry<SSLConsumer, ProtocolVersion[]>[])(new Map.Entry[] {
             new SimpleImmutableEntry<SSLConsumer, ProtocolVersion[]>(
-                NewSessionTicket.handshakeConsumer,
-                ProtocolVersion.PROTOCOLS_OF_13
-        )
+                 NewSessionTicket.handshake12Consumer,
+                 ProtocolVersion.PROTOCOLS_TO_12
+            ),
+            new SimpleImmutableEntry<SSLConsumer, ProtocolVersion[]>(
+                 NewSessionTicket.handshakeConsumer,
+                 ProtocolVersion.PROTOCOLS_OF_13
+            )
         }),
         (Map.Entry<HandshakeProducer, ProtocolVersion[]>[])(new Map.Entry[] {
             new SimpleImmutableEntry<HandshakeProducer, ProtocolVersion[]>(
-                NewSessionTicket.handshakeProducer,
-                ProtocolVersion.PROTOCOLS_OF_13
-        )
+                 NewSessionTicket.handshake12Producer,
+                 ProtocolVersion.PROTOCOLS_TO_12
+            )
         })),
     END_OF_EARLY_DATA           ((byte)0x05, "end_of_early_data"),
 
--- a/src/java.base/share/classes/sun/security/ssl/SSLSessionContextImpl.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLSessionContextImpl.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,11 +33,34 @@
 import javax.net.ssl.SSLSessionContext;
 
 import sun.security.action.GetIntegerAction;
+import sun.security.action.GetPropertyAction;
 import sun.security.util.Cache;
 
 
+/**
+ * @systemProperty jdk.tls.server.enableSessionTicketExtension} determines if the
+ * server will provide stateless session tickets, if the client supports it,
+ * as described in RFC 5077 and RFC 8446.  a stateless session ticket
+ * contains the encrypted server's state which saves server resources.
+ *
+ * {@systemProperty jdk.tls.client.enableSessionTicketExtension} determines if the
+ * client will send an extension in the ClientHello in the pre-TLS 1.3.
+ * This extension allows the client to accept the server's session state for
+ * Server Side stateless resumption (RFC 5077).  Setting the property to
+ * "true" turns this on, by default it is false.  For TLS 1.3, the system
+ * property is not needed as this support is part of the spec.
+ *
+ * {@systemProperty jdk.tls.server.sessionTicketTimeout} determines how long
+ * a session in the server cache or the stateless resumption tickets are
+ * available for use.  The value set by the property can be modified by
+ * {@code SSLSessionContext.setSessionTimeout()} during runtime.
+ *
+ */
+
 final class SSLSessionContextImpl implements SSLSessionContext {
     private final static int DEFAULT_MAX_CACHE_SIZE = 20480;
+    // Default lifetime of a session. 24 hours
+    final static int DEFAULT_SESSION_TIMEOUT = 86400;
 
     private final Cache<SessionId, SSLSessionImpl> sessionCache;
                                         // session cache, session id as key
@@ -46,16 +69,24 @@
     private int cacheLimit;             // the max cache size
     private int timeout;                // timeout in seconds
 
+    // Does this context support stateless session (RFC 5077)
+    private boolean statelessSession = true;
+
     // package private
-    SSLSessionContextImpl() {
-        cacheLimit = getDefaultCacheLimit();    // default cache size
-        timeout = 86400;                        // default, 24 hours
+    SSLSessionContextImpl(boolean server) {
+        timeout = DEFAULT_SESSION_TIMEOUT;
+        cacheLimit = getDefaults(server);    // default cache size
 
         // use soft reference
         sessionCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
         sessionHostPortCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
     }
 
+    // Stateless sessions when available, but there is a cache
+    boolean statelessEnabled() {
+        return statelessSession;
+    }
+
     /**
      * Returns the <code>SSLSession</code> bound to the specified session id.
      */
@@ -163,8 +194,7 @@
     }
 
     private static String getKey(String hostname, int port) {
-        return (hostname + ":" +
-            String.valueOf(port)).toLowerCase(Locale.ENGLISH);
+        return (hostname + ":" + port).toLowerCase(Locale.ENGLISH);
     }
 
     // cache a SSLSession
@@ -197,8 +227,51 @@
         }
     }
 
-    private static int getDefaultCacheLimit() {
+    private int getDefaults(boolean server) {
         try {
+            String st;
+
+            // Property for Session Cache state
+            if (server) {
+                st = GetPropertyAction.privilegedGetProperty(
+                        "jdk.tls.server.enableSessionTicketExtension", "true");
+            } else {
+                st = GetPropertyAction.privilegedGetProperty(
+                        "jdk.tls.client.enableSessionTicketExtension", "true");
+            }
+            if (st.compareToIgnoreCase("false") == 0) {
+                statelessSession = false;
+            }
+
+            // Property for Session Ticket Timeout.  The value can be changed
+            // by SSLSessionContext.setSessionTimeout(int)
+            String s = GetPropertyAction.privilegedGetProperty(
+                    "jdk.tls.server.sessionTicketTimeout");
+            if (s != null) {
+                try {
+                    int t = Integer.parseInt(s);
+                    if (t < 0 ||
+                            t > NewSessionTicket.MAX_TICKET_LIFETIME) {
+                        timeout = DEFAULT_SESSION_TIMEOUT;
+                        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
+                            SSLLogger.warning("Invalid timeout given " +
+                                    "jdk.tls.server.sessionTicketTimeout: " + t +
+                                    ".  Set to default value " + timeout);
+                        }
+                    } else {
+                        timeout = t;
+                    }
+                } catch (NumberFormatException e) {
+                    setSessionTimeout(DEFAULT_SESSION_TIMEOUT);
+                    if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
+                        SSLLogger.warning("Invalid timeout for " +
+                                "jdk.tls.server.sessionTicketTimeout: " + s +
+                                ".  Set to default value " + timeout);
+
+                    }
+                }
+            }
+
             int defaultCacheLimit = GetIntegerAction.privilegedGetProperty(
                     "javax.net.ssl.sessionCacheSize", DEFAULT_MAX_CACHE_SIZE);
 
--- a/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java	Wed Jun 12 10:02:49 2019 +0530
@@ -24,8 +24,12 @@
  */
 package sun.security.ssl;
 
+import sun.security.x509.X509CertImpl;
+
+import java.io.IOException;
 import java.math.BigInteger;
 import java.net.InetAddress;
+import java.nio.ByteBuffer;
 import java.security.Principal;
 import java.security.PrivateKey;
 import java.security.cert.CertificateEncodingException;
@@ -40,8 +44,11 @@
 import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.concurrent.locks.ReentrantLock;
 import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
 import javax.net.ssl.ExtendedSSLSession;
+import javax.net.ssl.SNIHostName;
 import javax.net.ssl.SNIServerName;
+import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLPeerUnverifiedException;
 import javax.net.ssl.SSLPermission;
 import javax.net.ssl.SSLSessionBindingEvent;
@@ -251,6 +258,371 @@
         }
     }
 
+    /**
+     * < 2 bytes > protocolVersion
+     * < 2 bytes > cipherSuite
+     * < 2 bytes > localSupportedSignAlgs entries
+     *   < 2 bytes per entries > localSupportedSignAlgs
+     * < 2 bytes > preSharedKey length
+     * < length in bytes > preSharedKey
+     * < 1 byte > pskIdentity length
+     * < length in bytes > pskIdentity
+     * < 1 byte > masterSecret length
+     *   < 1 byte > masterSecret algorithm length
+     *   < length in bytes > masterSecret algorithm
+     *   < 2 bytes > masterSecretKey length
+     *   < length in bytes> masterSecretKey
+     * < 1 byte > useExtendedMasterSecret
+     * < 1 byte > identificationProtocol length
+     * < length in bytes > identificationProtocol
+     * < 1 byte > serverNameIndication length
+     * < length in bytes > serverNameIndication
+     * < 1 byte > Number of requestedServerNames entries
+     *   < 1 byte > ServerName length
+     *   < length in bytes > ServerName
+     * < 4 bytes > creationTime
+     * < 1 byte > Length of peer host
+     *   < length in bytes > peer host
+     * < 2 bytes> peer port
+     * < 1 byte > Number of peerCerts entries
+     *   < 4 byte > peerCert length
+     *   < length in bytes > peerCert
+     * < 1 byte > localCerts type (Cert, PSK, Anonymous)
+     *   Certificate
+     *     < 1 byte > Number of Certificate entries
+     *       < 4 byte> Certificate length
+     *       < length in bytes> Certificate
+     *   PSK
+     *     < 1 byte > Number of PSK entries
+     *       < 1 bytes > PSK algorithm length
+     *       < length in bytes > PSK algorithm string
+     *       < 4 bytes > PSK key length
+     *       < length in bytes> PSK key
+     *       < 4 bytes > PSK identity length
+     *       < length in bytes> PSK identity
+     *   Anonymous
+     *     < 1 byte >
+    */
+
+    SSLSessionImpl(HandshakeContext hc, ByteBuffer buf) throws IOException {
+        int i = 0;
+        byte[] b;
+
+        this.localSupportedSignAlgs = new ArrayList<>();
+
+        boundValues = null;
+
+        this.protocolVersion = ProtocolVersion.valueOf(Short.toUnsignedInt(buf.getShort()));
+
+        if (protocolVersion.useTLS13PlusSpec()) {
+            this.sessionId = new SessionId(false, null);
+        } else {
+            // The CH session id may reset this if it's provided
+            this.sessionId = new SessionId(true,
+                    hc.sslContext.getSecureRandom());
+        }
+
+        this.cipherSuite = CipherSuite.valueOf(Short.toUnsignedInt(buf.getShort()));
+
+        // Local Supported signature algorithms
+        i = Short.toUnsignedInt(buf.getShort());
+        while (i-- > 0) {
+            this.localSupportedSignAlgs.add(SignatureScheme.valueOf(
+                    Short.toUnsignedInt(buf.getShort())));
+        }
+
+        // PSK
+        i = Short.toUnsignedInt(buf.getShort());
+        if (i > 0) {
+            b = new byte[i];
+            // Get algorithm string
+            buf.get(b, 0, i);
+            // Encoded length
+            i = Short.toUnsignedInt(buf.getShort());
+            // Encoded SecretKey
+            b = new byte[i];
+            buf.get(b);
+            this.preSharedKey = new SecretKeySpec(b, "TlsMasterSecret");
+        } else {
+            this.preSharedKey = null;
+        }
+
+        // PSK identity
+        i = buf.get();
+        if (i > 0) {
+            b = new byte[i];
+            buf.get(b);
+            this.pskIdentity = b;
+        } else {
+            this.pskIdentity = null;
+        }
+
+        // Master secret length of secret key algorithm  (one byte)
+        i = buf.get();
+        if (i > 0) {
+            b = new byte[i];
+            // Get algorithm string
+            buf.get(b, 0, i);
+            // Encoded length
+            i = Short.toUnsignedInt(buf.getShort());
+            // Encoded SecretKey
+            b = new byte[i];
+            buf.get(b);
+            this.masterSecret = new SecretKeySpec(b, "TlsMasterSecret");
+        } else {
+            this.masterSecret = null;
+        }
+        // Use extended master secret
+        this.useExtendedMasterSecret = (buf.get() != 0);
+
+        // Identification Protocol
+        i = buf.get();
+        if (i == 0) {
+            identificationProtocol = null;
+        } else {
+            b = new byte[i];
+            identificationProtocol =
+                    buf.get(b, 0, i).asCharBuffer().toString();
+        }
+
+        // SNI
+        i = buf.get();  // length
+        if (i == 0) {
+            serverNameIndication = null;
+        } else {
+            b = new byte[i];
+            buf.get(b, 0, b.length);
+            serverNameIndication = new SNIHostName(b);
+        }
+
+        // List of SNIServerName
+        int len = Short.toUnsignedInt(buf.getShort());
+        if (len == 0) {
+            this.requestedServerNames = Collections.<SNIServerName>emptyList();
+        } else {
+            requestedServerNames = new ArrayList<>();
+            while (len > 0) {
+                int l = buf.get();
+                b = new byte[l];
+                buf.get(b, 0, l);
+                requestedServerNames.add(new SNIHostName(new String(b)));
+                len--;
+            }
+        }
+
+        // Get creation time
+        this.creationTime = buf.getLong();
+
+        // Get Peer host & port
+        i = Byte.toUnsignedInt(buf.get());
+        if (i == 0) {
+            this.host = new String();
+        } else {
+            b = new byte[i];
+            this.host = buf.get(b).toString();
+        }
+        this.port = Short.toUnsignedInt(buf.getShort());
+
+        // Peer certs
+        i = buf.get();
+        if (i == 0) {
+            this.peerCerts = null;
+        } else {
+            this.peerCerts = new X509Certificate[i];
+            int j = 0;
+            while (i > j) {
+                b = new byte[buf.getInt()];
+                buf.get(b);
+                try {
+                    this.peerCerts[j] = new X509CertImpl(b);
+                } catch (Exception e) {
+                    throw new IOException(e);
+                }
+                j++;
+            }
+        }
+
+        // Get local certs of PSK
+        switch (buf.get()) {
+            case 0:
+                break;
+            case 1:
+                // number of certs
+                len = buf.get();
+                this.localCerts = new X509Certificate[len];
+                i = 0;
+                while (len > i) {
+                    b = new byte[buf.getInt()];
+                    buf.get(b);
+                    try {
+                        this.localCerts[i] = new X509CertImpl(b);
+                    } catch (Exception e) {
+                        throw new IOException(e);
+                    }
+                    i++;
+                }
+                break;
+            case 2:
+                // pre-shared key
+                // Length of pre-shared key algorithm  (one byte)
+                i = buf.get();
+                b = new byte[i];
+                String alg = buf.get(b, 0, i).asCharBuffer().toString();
+                // Get length of encoding
+                i = Short.toUnsignedInt(buf.getShort());
+                // Get encoding
+                b = new byte[i];
+                buf.get(b);
+                this.preSharedKey = new SecretKeySpec(b, alg);
+                // Get identity len
+                this.pskIdentity = new byte[buf.get()];
+                buf.get(pskIdentity);
+                break;
+            default:
+                throw new SSLException("Failed local certs of session.");
+        }
+
+        context = (SSLSessionContextImpl)
+                hc.sslContext.engineGetServerSessionContext();
+    }
+
+    /**
+     * Write out a SSLSessionImpl in a byte array for a stateless session ticket
+     */
+    byte[] write() throws Exception {
+        byte[] b;
+        HandshakeOutStream hos = new HandshakeOutStream(null);
+
+        hos.putInt16(protocolVersion.id);
+        hos.putInt16(cipherSuite.id);
+
+        // Local Supported signature algorithms
+        int l = localSupportedSignAlgs.size();
+        hos.putInt16(l);
+        SignatureScheme[] sig = new SignatureScheme[l];
+        localSupportedSignAlgs.toArray(sig);
+        for (SignatureScheme s : sig) {
+            hos.putInt16(s.id);
+        }
+
+        // PSK
+        if (preSharedKey == null ||
+                preSharedKey.getAlgorithm() == null) {
+            hos.putInt16(0);
+        } else {
+            hos.putInt16(preSharedKey.getAlgorithm().length());
+            if (preSharedKey.getAlgorithm().length() != 0) {
+                hos.write(preSharedKey.getAlgorithm().getBytes());
+            }
+            b = preSharedKey.getEncoded();
+            hos.putInt16(b.length);
+            hos.write(b, 0, b.length);
+        }
+
+        // PSK Identity
+        if (pskIdentity == null) {
+            hos.putInt8(0);
+        } else {
+            hos.putInt8(pskIdentity.length);
+            hos.write(pskIdentity, 0, pskIdentity.length);
+        }
+
+        // Master Secret
+        if (getMasterSecret() == null ||
+                getMasterSecret().getAlgorithm() == null) {
+            hos.putInt8(0);
+        } else {
+            hos.putInt8(getMasterSecret().getAlgorithm().length());
+            if (getMasterSecret().getAlgorithm().length() != 0) {
+                hos.write(getMasterSecret().getAlgorithm().getBytes());
+            }
+            b = getMasterSecret().getEncoded();
+            hos.putInt16(b.length);
+            hos.write(b, 0, b.length);
+        }
+
+        hos.putInt8(useExtendedMasterSecret ? 1 : 0);
+
+        // Identification Protocol
+        if (identificationProtocol == null) {
+            hos.putInt8(0);
+        } else {
+            hos.putInt8(identificationProtocol.length());
+            hos.write(identificationProtocol.getBytes(), 0,
+                    identificationProtocol.length());
+        }
+
+        // SNI
+        if (serverNameIndication == null) {
+            hos.putInt8(0);
+        } else {
+            b = serverNameIndication.getEncoded();
+            hos.putInt8(b.length);
+            hos.write(b, 0, b.length);
+        }
+
+        // List of SNIServerName
+        hos.putInt16(requestedServerNames.size());
+        if (requestedServerNames.size() > 0) {
+            for (SNIServerName host: requestedServerNames) {
+                b = host.getEncoded();
+                hos.putInt8(b.length);
+                hos.write(b, 0, b.length);
+            }
+        }
+
+        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
+        hos.writeBytes(buffer.putLong(creationTime).array());
+
+        // peer Host & Port
+        if (host == null || host.length() == 0) {
+            hos.putInt8(0);
+        } else {
+            hos.putInt8(host.length());
+            hos.writeBytes(host.getBytes());
+        }
+        hos.putInt16(port);
+
+        // Peer cert
+        if (peerCerts == null || peerCerts.length == 0) {
+            hos.putInt8(0);
+        } else {
+            hos.putInt8(peerCerts.length);
+            for (X509Certificate c : peerCerts) {
+                b = c.getEncoded();
+                hos.putInt32(b.length);
+                hos.writeBytes(b);
+            }
+        }
+
+        // Client identity
+        if (localCerts != null && localCerts.length > 0) {
+            // certificate based
+            hos.putInt8(1);
+            hos.putInt8(localCerts.length);
+            for (X509Certificate c : localCerts) {
+                b = c.getEncoded();
+                hos.putInt32(b.length);
+                hos.writeBytes(b);
+            }
+        } else if (preSharedKey != null) {
+            // pre-shared key
+            hos.putInt8(2);
+            hos.putInt8(preSharedKey.getAlgorithm().length());
+            hos.write(preSharedKey.getAlgorithm().getBytes());
+            b = preSharedKey.getEncoded();
+            hos.putInt32(b.length);
+            hos.writeBytes(b);
+            hos.putInt32(pskIdentity.length);
+            hos.writeBytes(pskIdentity);
+        } else {
+            // anonymous
+            hos.putInt8(0);
+        }
+
+        return hos.toByteArray();
+    }
+
     void setMasterSecret(SecretKey secret) {
         masterSecret = secret;
     }
@@ -333,6 +705,10 @@
         }
     }
 
+    byte[] getPskIdentity() {
+        return pskIdentity;
+    }
+
     void setPeerCertificates(X509Certificate[] peer) {
         if (peerCerts == null) {
             peerCerts = peer;
@@ -400,8 +776,12 @@
      * maximum lifetime in any case.
      */
     boolean isRejoinable() {
+        // TLS 1.3 can have no session id
+        if (protocolVersion.useTLS13PlusSpec()) {
+            return (!invalidated && isLocalAuthenticationValid());
+        }
         return sessionId != null && sessionId.length() != 0 &&
-            !invalidated && isLocalAuthenticationValid();
+                !invalidated && isLocalAuthenticationValid();
     }
 
     @Override
--- a/src/java.base/share/classes/sun/security/ssl/ServerHello.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/ServerHello.java	Wed Jun 12 10:02:49 2019 +0530
@@ -47,6 +47,8 @@
 import sun.security.ssl.SSLHandshake.HandshakeMessage;
 import sun.security.ssl.SupportedVersionsExtension.SHSupportedVersionsSpec;
 
+import static sun.security.ssl.SSLExtension.SH_SESSION_TICKET;
+
 /**
  * Pack of the ServerHello/HelloRetryRequest handshake message.
  */
@@ -337,6 +339,15 @@
                 shc.handshakeProducers.put(SSLHandshake.SERVER_HELLO_DONE.id,
                         SSLHandshake.SERVER_HELLO_DONE);
             } else {
+                // stateless and use the client session id (RFC 5077 3.4)
+                if (shc.statelessResumption) {
+                    shc.resumingSession = new SSLSessionImpl(shc.resumingSession,
+                            (clientHello.sessionId.length() == 0) ?
+                                    new SessionId(true,
+                                            shc.sslContext.getSecureRandom()) :
+                                    new SessionId(clientHello.sessionId.getId())
+                    );
+                }
                 shc.handshakeSession = shc.resumingSession;
                 shc.negotiatedProtocol =
                         shc.resumingSession.getProtocolVersion();
@@ -491,6 +502,9 @@
             ServerHandshakeContext shc = (ServerHandshakeContext)context;
             ClientHelloMessage clientHello = (ClientHelloMessage)message;
 
+            SSLSessionContextImpl sessionCache = (SSLSessionContextImpl)
+                    shc.sslContext.engineGetServerSessionContext();
+
             // If client hasn't specified a session we can resume, start a
             // new one and choose its cipher suite and compression options,
             // unless new session creation is disabled for this connection!
@@ -546,8 +560,6 @@
                         shc.resumingSession.consumePreSharedKey());
 
                 // The session can't be resumed again---remove it from cache
-                SSLSessionContextImpl sessionCache = (SSLSessionContextImpl)
-                    shc.sslContext.engineGetServerSessionContext();
                 sessionCache.remove(shc.resumingSession.getSessionId());
             }
 
@@ -679,6 +691,11 @@
             // Update the context for master key derivation.
             shc.handshakeKeyDerivation = kd;
 
+            // Check if the server supports stateless resumption
+            if (sessionCache.statelessEnabled()) {
+                shc.statelessResumption = true;
+            }
+
             // The handshake message has been delivered.
             return null;
         }
@@ -1098,9 +1115,23 @@
                     throw chc.conContext.fatal(Alert.PROTOCOL_VERSION,
                         "New session creation is disabled");
                 }
-                chc.handshakeSession = new SSLSessionImpl(chc,
-                        chc.negotiatedCipherSuite,
-                        serverHello.sessionId);
+
+                if (serverHello.sessionId.length() == 0 &&
+                        chc.statelessResumption) {
+                    SessionId newId = new SessionId(true,
+                            chc.sslContext.getSecureRandom());
+                    chc.handshakeSession = new SSLSessionImpl(chc,
+                            chc.negotiatedCipherSuite, newId);
+
+                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                        SSLLogger.fine("Locally assigned Session Id: " +
+                                newId.toString());
+                    }
+                } else {
+                    chc.handshakeSession = new SSLSessionImpl(chc,
+                            chc.negotiatedCipherSuite,
+                            serverHello.sessionId);
+                }
                 chc.handshakeSession.setMaximumPacketSize(
                         chc.sslConfig.maximumPacketSize);
             }
@@ -1127,6 +1158,11 @@
                 chc.conContext.consumers.putIfAbsent(
                         ContentType.CHANGE_CIPHER_SPEC.id,
                         ChangeCipherSpec.t10Consumer);
+                if (chc.statelessResumption) {
+                    chc.handshakeConsumers.putIfAbsent(
+                            SSLHandshake.NEW_SESSION_TICKET.id,
+                            SSLHandshake.NEW_SESSION_TICKET);
+                }
                 chc.handshakeConsumers.put(
                         SSLHandshake.FINISHED.id,
                         SSLHandshake.FINISHED);
--- a/src/java.base/share/classes/sun/security/ssl/SessionId.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SessionId.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  * @author David Brownell
  */
 final class SessionId {
-    private static final int MAX_LENGTH = 32;
+    static final int MAX_LENGTH = 32;
     private final byte[] sessionId;          // max 32 bytes
 
     // Constructs a new session ID ... perhaps for a rejoinable session
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,539 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.ssl;
+
+import sun.security.action.GetPropertyAction;
+import sun.security.ssl.SSLExtension.ExtensionConsumer;
+import sun.security.ssl.SSLExtension.SSLExtensionSpec;
+import sun.security.ssl.SSLHandshake.HandshakeMessage;
+import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;
+import sun.security.util.HexDumpEncoder;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.net.ssl.SSLProtocolException;
+
+import static sun.security.ssl.SSLExtension.CH_SESSION_TICKET;
+import static sun.security.ssl.SSLExtension.SH_SESSION_TICKET;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.Locale;
+
+/**
+ * SessionTicketExtension is an implementation of RFC 5077 with some internals
+ * that are used for stateless operation in TLS 1.3.
+ *
+ * {@systemProperty jdk.tls.server.statelessKeyTimeout} can override the default
+ * amount of time, in seconds, for how long a randomly-generated key and
+ * parameters can be used before being regenerated.  The key material is used
+ * to encrypt the stateless session ticket that is sent to the client that will
+ * be used during resumption.  Default is 3600 seconds (1 hour)
+ *
+ */
+
+final class SessionTicketExtension {
+
+    static final HandshakeProducer chNetworkProducer =
+            new T12CHSessionTicketProducer();
+    static final ExtensionConsumer chOnLoadConsumer =
+            new T12CHSessionTicketConsumer();
+    static final HandshakeProducer shNetworkProducer =
+            new T12SHSessionTicketProducer();
+    static final ExtensionConsumer shOnLoadConsumer =
+            new T12SHSessionTicketConsumer();
+
+    static final SSLStringizer steStringizer = new SessionTicketStringizer();
+
+    // Time in milliseconds until key is changed for encrypting session state
+    private static final int TIMEOUT_DEFAULT = 3600 * 1000;
+    private static final int keyTimeout;
+    private static int currentKeyID = new SecureRandom().nextInt();
+    private static final int KEYLEN = 256;
+
+    static {
+        String s = GetPropertyAction.privilegedGetProperty(
+                "jdk.tls.server.statelessKeyTimeout");
+        if (s != null) {
+            int kt;
+            try {
+                kt = Integer.parseInt(s) * 1000;  // change to ms
+                if (kt < 0 ||
+                        kt > NewSessionTicket.MAX_TICKET_LIFETIME) {
+                    if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
+                        SSLLogger.warning("Invalid timeout for " +
+                                "jdk.tls.server.statelessKeyTimeout: " +
+                                kt + ".  Set to default value " +
+                                TIMEOUT_DEFAULT + "sec");
+                    }
+                    kt = TIMEOUT_DEFAULT;
+                }
+            } catch (NumberFormatException e) {
+                kt = TIMEOUT_DEFAULT;
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
+                    SSLLogger.warning("Invalid timeout for " +
+                            "jdk.tls.server.statelessKeyTimeout: " + s +
+                            ".  Set to default value " + TIMEOUT_DEFAULT +
+                            "sec");
+                }
+            }
+            keyTimeout = kt;
+        } else {
+            keyTimeout = TIMEOUT_DEFAULT;
+        }
+    }
+
+    // Crypto key context for session state.  Used with stateless operation.
+    final static class StatelessKey {
+        final long timeout;
+        final SecretKey key;
+        final int num;
+
+        StatelessKey(HandshakeContext hc, int newNum) {
+            SecretKey k = null;
+            try {
+                KeyGenerator kg = KeyGenerator.getInstance("AES");
+                kg.init(KEYLEN, hc.sslContext.getSecureRandom());
+                k = kg.generateKey();
+            } catch (NoSuchAlgorithmException e) {
+                // should not happen;
+            }
+            key = k;
+            timeout = System.currentTimeMillis() + keyTimeout;
+            num = newNum;
+            hc.sslContext.keyHashMap.put(Integer.valueOf(num), this);
+        }
+
+        // Check if key needs to be changed
+        boolean isExpired() {
+            return ((System.currentTimeMillis()) > timeout);
+        }
+
+        // Check if this key is ready for deletion.
+        boolean isInvalid(long sessionTimeout) {
+            return ((System.currentTimeMillis()) > (timeout + sessionTimeout));
+        }
+    }
+
+    private static final class KeyState {
+
+        // Get a key with a specific key number
+        static StatelessKey getKey(HandshakeContext hc, int num)  {
+            StatelessKey ssk = hc.sslContext.keyHashMap.get(num);
+
+            if (ssk == null || ssk.isInvalid(getSessionTimeout(hc))) {
+                return null;
+            }
+            return ssk;
+        }
+
+        // Get the current valid key, this will generate a new key if needed
+        static StatelessKey getCurrentKey(HandshakeContext hc) {
+            StatelessKey ssk = hc.sslContext.keyHashMap.get(currentKeyID);
+
+            if (ssk != null && !ssk.isExpired()) {
+                return ssk;
+            }
+            return nextKey(hc);
+        }
+
+        // This method locks when the first getCurrentKey() finds it to be too
+        // old and create a new key to replace the current key.  After the new
+        // key established, the lock can be released so following
+        // operations will start using the new key.
+        // The first operation will take a longer code path by generating the
+        // next key and cleaning up old keys.
+        private static StatelessKey nextKey(HandshakeContext hc) {
+            StatelessKey ssk;
+
+            synchronized (hc.sslContext.keyHashMap) {
+                // If the current key is no longer expired, it was already
+                // updated by a previous operation and we can return.
+                ssk = hc.sslContext.keyHashMap.get(currentKeyID);
+                if (ssk != null && !ssk.isExpired()) {
+                    return ssk;
+                }
+                int newNum;
+                if (currentKeyID == Integer.MAX_VALUE) {
+                    newNum = 0;
+                } else {
+                    newNum = currentKeyID + 1;
+                }
+                // Get new key
+                ssk = new StatelessKey(hc, newNum);
+                currentKeyID = newNum;
+                // Release lock since the new key is ready to be used.
+            }
+
+            // Clean up any old keys, then return the current key
+            cleanup(hc);
+            return ssk;
+        }
+
+        // Deletes any invalid SessionStateKeys.
+        static void cleanup(HandshakeContext hc) {
+            int sessionTimeout = getSessionTimeout(hc);
+
+            StatelessKey ks;
+            for (Object o : hc.sslContext.keyHashMap.keySet().toArray()) {
+                Integer i = (Integer)o;
+                ks = hc.sslContext.keyHashMap.get(i);
+                if (ks.isInvalid(sessionTimeout)) {
+                    try {
+                        ks.key.destroy();
+                    } catch (Exception e) {
+                        // Suppress
+                    }
+                    hc.sslContext.keyHashMap.remove(i);
+                }
+            }
+        }
+
+        static int getSessionTimeout(HandshakeContext hc) {
+            return hc.sslContext.engineGetServerSessionContext().
+                    getSessionTimeout() * 1000;
+        }
+    }
+
+    /**
+     * This class contains the session state that is in the session ticket.
+     * Using the key associated with the ticket, the class encrypts and
+     * decrypts the data, but does not interpret the data.
+     */
+    static final class SessionTicketSpec implements SSLExtensionSpec {
+        private static final int GCM_TAG_LEN = 128;
+        ByteBuffer data;
+        static final ByteBuffer zero = ByteBuffer.wrap(new byte[0]);
+
+        SessionTicketSpec() {
+            data = zero;
+        }
+
+        SessionTicketSpec(byte[] b) throws IOException {
+            this(ByteBuffer.wrap(b));
+        }
+
+        SessionTicketSpec(ByteBuffer buf) throws IOException {
+            if (buf == null) {
+                throw new SSLProtocolException(
+                        "SessionTicket buffer too small");
+            }
+            if (buf.remaining() > 65536) {
+                throw new SSLProtocolException(
+                        "SessionTicket buffer too large. " + buf.remaining());
+            }
+
+            data = buf;
+        }
+
+        public byte[] encrypt(HandshakeContext hc, SSLSessionImpl session)
+                throws IOException {
+            byte[] encrypted;
+            StatelessKey key = KeyState.getCurrentKey(hc);
+            byte[] iv = new byte[16];
+
+            try {
+                SecureRandom random = hc.sslContext.getSecureRandom();
+                random.nextBytes(iv);
+                Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
+                c.init(Cipher.ENCRYPT_MODE, key.key,
+                        new GCMParameterSpec(GCM_TAG_LEN, iv));
+                c.updateAAD(new byte[] {
+                        (byte)(key.num >>> 24),
+                        (byte)(key.num >>> 16),
+                        (byte)(key.num >>> 8),
+                        (byte)(key.num)}
+                );
+                encrypted = c.doFinal(session.write());
+
+                byte[] result = new byte[encrypted.length + Integer.BYTES +
+                        iv.length];
+                result[0] = (byte)(key.num >>> 24);
+                result[1] = (byte)(key.num >>> 16);
+                result[2] = (byte)(key.num >>> 8);
+                result[3] = (byte)(key.num);
+                System.arraycopy(iv, 0, result, Integer.BYTES, iv.length);
+                System.arraycopy(encrypted, 0, result,
+                        Integer.BYTES + iv.length, encrypted.length);
+                return result;
+            } catch (Exception e) {
+                throw hc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, e);
+            }
+        }
+
+        ByteBuffer decrypt(HandshakeContext hc) {
+            int keyID;
+            byte[] iv;
+            try {
+                keyID = data.getInt();
+                StatelessKey key = KeyState.getKey(hc, keyID);
+                if (key == null) {
+                    return null;
+                }
+
+                iv = new byte[16];
+                data.get(iv);
+                Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
+                c.init(Cipher.DECRYPT_MODE, key.key,
+                        new GCMParameterSpec(GCM_TAG_LEN, iv));
+                c.updateAAD(new byte[] {
+                        (byte)(keyID >>> 24),
+                        (byte)(keyID >>> 16),
+                        (byte)(keyID >>> 8),
+                        (byte)(keyID)}
+                );
+                /*
+                return ByteBuffer.wrap(c.doFinal(data,
+                        Integer.BYTES + iv.length,
+                        data.length - (Integer.BYTES + iv.length)));
+                 */
+                ByteBuffer out;
+                out = ByteBuffer.allocate(data.remaining() - GCM_TAG_LEN / 8);
+                c.doFinal(data, out);
+                out.flip();
+                return out;
+            } catch (Exception e) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Decryption failed." + e.getMessage());
+                }
+            }
+            return null;
+        }
+
+        byte[] getEncoded() {
+            byte[] out = new byte[data.capacity()];
+            data.duplicate().get(out);
+            return out;
+        }
+
+        @Override
+        public String toString() {
+            if (data == null) {
+                return "<null>";
+            }
+            if (data.capacity() == 0) {
+                return "<empty>";
+            }
+
+            MessageFormat messageFormat = new MessageFormat(
+                    "  \"ticket\" : '{'\n" +
+                            "{0}\n" +
+                            "  '}'",
+                    Locale.ENGLISH);
+            HexDumpEncoder hexEncoder = new HexDumpEncoder();
+
+            Object[] messageFields = {
+                    Utilities.indent(hexEncoder.encode(data.duplicate()),
+                            "    "),
+            };
+
+            return messageFormat.format(messageFields);
+        }
+    }
+
+    static final class SessionTicketStringizer implements SSLStringizer {
+        SessionTicketStringizer() {}
+
+        @Override
+        public String toString(ByteBuffer buffer) {
+            try {
+                return new SessionTicketSpec(buffer).toString();
+            } catch (IOException e) {
+                return e.getMessage();
+            }
+        }
+    }
+
+    private static final class T12CHSessionTicketProducer
+            extends SupportedGroups implements HandshakeProducer {
+        T12CHSessionTicketProducer() {
+        }
+
+        @Override
+        public byte[] produce(ConnectionContext context,
+                HandshakeMessage message) throws IOException {
+
+            ClientHandshakeContext chc = (ClientHandshakeContext)context;
+
+            // If the context does not allow stateless tickets, exit
+            if (!((SSLSessionContextImpl)chc.sslContext.
+                    engineGetClientSessionContext()).statelessEnabled()) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Stateless resumption not supported");
+                }
+                return null;
+            }
+
+            chc.statelessResumption = true;
+
+            // If resumption is not in progress, return an empty value
+            if (!chc.isResumption || chc.resumingSession == null) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Stateless resumption supported");
+                }
+                return new SessionTicketSpec().getEncoded();
+            }
+
+            if (chc.localSupportedSignAlgs == null) {
+                chc.localSupportedSignAlgs =
+                        SignatureScheme.getSupportedAlgorithms(
+                                chc.algorithmConstraints, chc.activeProtocols);
+            }
+
+            return chc.resumingSession.getPskIdentity();
+        }
+
+    }
+
+    private static final class T12CHSessionTicketConsumer
+            implements ExtensionConsumer {
+        T12CHSessionTicketConsumer() {
+        }
+
+        @Override
+        public void consume(ConnectionContext context,
+                HandshakeMessage message, ByteBuffer buffer)
+                throws IOException {
+            ServerHandshakeContext shc = (ServerHandshakeContext) context;
+
+            // Skip if extension is not provided
+            if (!shc.sslConfig.isAvailable(CH_SESSION_TICKET)) {
+                return;
+            }
+
+            // Skip consumption if we are already in stateless resumption
+            if (shc.statelessResumption) {
+                return;
+            }
+            // If the context does not allow stateless tickets, exit
+            SSLSessionContextImpl cache = (SSLSessionContextImpl)shc.sslContext
+                    .engineGetServerSessionContext();
+            if (!cache.statelessEnabled()) {
+                return;
+            }
+
+            if (buffer.remaining() == 0) {
+                shc.statelessResumption = true;
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Client accepts session tickets.");
+                }
+                return;
+            }
+
+            // Parse the extension.
+            SessionTicketSpec spec;
+            try {
+                 spec = new SessionTicketSpec(buffer);
+            } catch (IOException | RuntimeException e) {
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("SessionTicket data invalid. Doing full " +
+                            "handshake.");
+                }
+                return;
+            }
+            ByteBuffer b = spec.decrypt(shc);
+            if (b != null) {
+                shc.resumingSession = new SSLSessionImpl(shc, b);
+                shc.isResumption = true;
+                shc.statelessResumption = true;
+                if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
+                    SSLLogger.fine("Valid stateless session ticket found");
+                }
+            }
+        }
+    }
+
+
+    private static final class T12SHSessionTicketProducer
+            extends SupportedGroups implements HandshakeProducer {
+        T12SHSessionTicketProducer() {
+        }
+
+        @Override
+        public byte[] produce(ConnectionContext context,
+                HandshakeMessage message) {
+
+            ServerHandshakeContext shc = (ServerHandshakeContext)context;
+
+            // If boolean is false, the CH did not have this extension
+            if (!shc.statelessResumption) {
+                return null;
+            }
+            // If the client has sent a SessionTicketExtension and stateless
+            // is enabled on the server, return an empty message.
+            // If the context does not allow stateless tickets, exit
+            SSLSessionContextImpl cache = (SSLSessionContextImpl)shc.sslContext
+                    .engineGetServerSessionContext();
+            if (cache.statelessEnabled()) {
+                return new byte[0];
+            }
+
+            shc.statelessResumption = false;
+            return null;
+        }
+    }
+
+    private static final class T12SHSessionTicketConsumer
+            implements ExtensionConsumer {
+        T12SHSessionTicketConsumer() {
+        }
+
+        @Override
+        public void consume(ConnectionContext context,
+                HandshakeMessage message, ByteBuffer buffer)
+                throws IOException {
+            ClientHandshakeContext chc = (ClientHandshakeContext) context;
+
+            // Skip if extension is not provided
+            if (!chc.sslConfig.isAvailable(SH_SESSION_TICKET)) {
+                chc.statelessResumption = false;
+                return;
+            }
+
+            // If the context does not allow stateless tickets, exit
+            if (!((SSLSessionContextImpl)chc.sslContext.
+                    engineGetClientSessionContext()).statelessEnabled()) {
+                chc.statelessResumption = false;
+                return;
+            }
+
+            try {
+                if (new SessionTicketSpec(buffer) == null) {
+                    return;
+                }
+                chc.statelessResumption = true;
+            } catch (IOException e) {
+                throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, e);
+            }
+        }
+    }
+}
--- a/src/java.base/share/classes/sun/security/ssl/TransportContext.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/TransportContext.java	Wed Jun 12 10:02:49 2019 +0530
@@ -159,14 +159,19 @@
                 if (handshakeContext == null) {
                     if (type == SSLHandshake.KEY_UPDATE.id ||
                             type == SSLHandshake.NEW_SESSION_TICKET.id) {
-                        if (isNegotiated &&
-                                protocolVersion.useTLS13PlusSpec()) {
-                            handshakeContext = new PostHandshakeContext(this);
-                        } else {
+                        if (!isNegotiated) {
+                            throw fatal(Alert.UNEXPECTED_MESSAGE,
+                                    "Unexpected unnegotiated post-handshake" +
+                                            " message: " +
+                                            SSLHandshake.nameOf(type));
+                        }
+                        if (type == SSLHandshake.KEY_UPDATE.id &&
+                                !protocolVersion.useTLS13PlusSpec()) {
                             throw fatal(Alert.UNEXPECTED_MESSAGE,
                                     "Unexpected post-handshake message: " +
                                     SSLHandshake.nameOf(type));
                         }
+                        handshakeContext = new PostHandshakeContext(this);
                     } else {
                         handshakeContext = sslConfig.isClientMode ?
                                 new ClientHandshakeContext(sslContext, this) :
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/sun/security/util/GCMParameters.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.util;
+
+import java.io.IOException;
+import java.security.AlgorithmParametersSpi;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import javax.crypto.spec.GCMParameterSpec;
+import sun.security.util.HexDumpEncoder;
+import sun.security.util.*;
+
+/**
+ * This class implements the parameter set used with
+ * GCM encryption, which is defined in RFC 5084 as follows:
+ *
+ * <pre>
+ *    GCMParameters ::= SEQUENCE {
+ *      aes-iv      OCTET STRING, -- recommended size is 12 octets
+ *      aes-tLen    AES-GCM-ICVlen DEFAULT 12 }
+ *
+ *    AES-GCM-ICVlen ::= INTEGER (12 | 13 | 14 | 15 | 16)
+ *
+ * </pre>
+ *
+ * @since 13
+ */
+public final class GCMParameters extends AlgorithmParametersSpi {
+
+    // the iv
+    private byte[] iv;
+    // the tag length in bytes
+    private int tLen;
+
+    public GCMParameters() {}
+
+    protected void engineInit(AlgorithmParameterSpec paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (!(paramSpec instanceof GCMParameterSpec)) {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+        GCMParameterSpec gps = (GCMParameterSpec) paramSpec;
+        // need to convert from bits to bytes for ASN.1 encoding
+        this.tLen = gps.getTLen()/8;
+        if (this.tLen < 12 || this.tLen > 16 ) {
+            throw new InvalidParameterSpecException
+                ("GCM parameter parsing error: unsupported tag len: " +
+                 this.tLen);
+        }
+        this.iv = gps.getIV();
+    }
+
+    protected void engineInit(byte[] encoded) throws IOException {
+        DerValue val = new DerValue(encoded);
+        // check if IV or params
+        if (val.tag == DerValue.tag_Sequence) {
+            byte[] iv = val.data.getOctetString();
+            int tLen;
+            if (val.data.available() != 0) {
+                tLen = val.data.getInteger();
+                if (tLen < 12 || tLen > 16 ) {
+                    throw new IOException
+                        ("GCM parameter parsing error: unsupported tag len: " +
+                         tLen);
+                }
+                if (val.data.available() != 0) {
+                    throw new IOException
+                        ("GCM parameter parsing error: extra data");
+                }
+            } else {
+                tLen = 12;
+            }
+            this.iv = iv.clone();
+            this.tLen = tLen;
+        } else {
+            throw new IOException("GCM parameter parsing error: no SEQ tag");
+        }
+    }
+
+    protected void engineInit(byte[] encoded, String decodingMethod)
+        throws IOException {
+        engineInit(encoded);
+    }
+
+    protected <T extends AlgorithmParameterSpec>
+            T engineGetParameterSpec(Class<T> paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (GCMParameterSpec.class.isAssignableFrom(paramSpec)) {
+            return paramSpec.cast(new GCMParameterSpec(tLen * 8, iv));
+        } else {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+    }
+
+    protected byte[] engineGetEncoded() throws IOException {
+        DerOutputStream out = new DerOutputStream();
+        DerOutputStream bytes = new DerOutputStream();
+
+        bytes.putOctetString(iv);
+        // Only put non-default values
+        if (tLen != 12) {
+            bytes.putInteger(tLen);
+        }
+        out.write(DerValue.tag_Sequence, bytes);
+        return out.toByteArray();
+    }
+
+    protected byte[] engineGetEncoded(String encodingMethod)
+        throws IOException {
+        return engineGetEncoded();
+    }
+
+    /*
+     * Returns a formatted string describing the parameters.
+     */
+    protected String engineToString() {
+        String LINE_SEP = System.lineSeparator();
+        HexDumpEncoder encoder = new HexDumpEncoder();
+        StringBuilder sb
+            = new StringBuilder(LINE_SEP + "    iv:" + LINE_SEP + "["
+                + encoder.encodeBuffer(iv) + "]");
+
+        sb.append(LINE_SEP + "tLen(bits):" + LINE_SEP + tLen*8 + LINE_SEP);
+        return sb.toString();
+    }
+}
--- a/src/java.base/share/native/libzip/Deflater.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/native/libzip/Deflater.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,9 +76,8 @@
     }
 }
 
-static void doSetDictionary(JNIEnv *env, jlong addr, jbyte *buf, jint len)
+static void checkSetDictionaryResult(JNIEnv *env, jlong addr, jint res)
 {
-    int res = deflateSetDictionary(jlong_to_ptr(addr), (Bytef *) buf, len);
     switch (res) {
     case Z_OK:
         break;
@@ -95,30 +94,33 @@
 Java_java_util_zip_Deflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
                                           jbyteArray b, jint off, jint len)
 {
-    jbyte *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+    int res;
+    Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
     if (buf == NULL) /* out of memory */
         return;
-    doSetDictionary(env, addr, buf + off, len);
+    res = deflateSetDictionary(jlong_to_ptr(addr), buf, len);
     (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
+    checkSetDictionaryResult(env, addr, res);
 }
 
 JNIEXPORT void JNICALL
 Java_java_util_zip_Deflater_setDictionaryBuffer(JNIEnv *env, jclass cls, jlong addr,
                                           jlong bufferAddr, jint len)
 {
-    jbyte *buf = jlong_to_ptr(bufferAddr);
-    doSetDictionary(env, addr, buf, len);
+    int res;
+    Bytef *buf = jlong_to_ptr(bufferAddr);
+    res = deflateSetDictionary(jlong_to_ptr(addr), buf, len);
+    checkSetDictionaryResult(env, addr, res);
 }
 
-static jlong doDeflate(JNIEnv *env, jobject this, jlong addr,
+static jint doDeflate(JNIEnv *env, jlong addr,
                        jbyte *input, jint inputLen,
                        jbyte *output, jint outputLen,
                        jint flush, jint params)
 {
     z_stream *strm = jlong_to_ptr(addr);
-    jint inputUsed = 0, outputUsed = 0;
-    int finished = 0;
     int setParams = params & 1;
+    int res;
 
     strm->next_in  = (Bytef *) input;
     strm->next_out = (Bytef *) output;
@@ -128,7 +130,24 @@
     if (setParams) {
         int strategy = (params >> 1) & 3;
         int level = params >> 3;
-        int res = deflateParams(strm, level, strategy);
+        res = deflateParams(strm, level, strategy);
+    } else {
+        res = deflate(strm, flush);
+    }
+    return res;
+}
+
+static jlong checkDeflateStatus(JNIEnv *env, jlong addr,
+                        jint inputLen,
+                        jint outputLen,
+                        jint params, int res)
+{
+    z_stream *strm = jlong_to_ptr(addr);
+    jint inputUsed = 0, outputUsed = 0;
+    int finished = 0;
+    int setParams = params & 1;
+
+    if (setParams) {
         switch (res) {
         case Z_OK:
             setParams = 0;
@@ -142,7 +161,6 @@
             return 0;
         }
     } else {
-        int res = deflate(strm, flush);
         switch (res) {
         case Z_STREAM_END:
             finished = 1;
@@ -169,6 +187,8 @@
     jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
     jbyte *output;
     jlong retVal;
+    jint res;
+
     if (input == NULL) {
         if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
             JNU_ThrowOutOfMemoryError(env, 0);
@@ -182,14 +202,13 @@
         return 0L;
     }
 
-    retVal = doDeflate(env, this, addr,
-            input + inputOff, inputLen,
-            output + outputOff, outputLen,
-            flush, params);
+     res = doDeflate(env, addr, input + inputOff, inputLen,output + outputOff,
+                     outputLen, flush, params);
 
     (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
     (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
 
+    retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
     return retVal;
 }
 
@@ -203,6 +222,7 @@
     jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
     jbyte *output;
     jlong retVal;
+    jint res;
     if (input == NULL) {
         if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
             JNU_ThrowOutOfMemoryError(env, 0);
@@ -210,13 +230,12 @@
     }
     output = jlong_to_ptr(outputBuffer);
 
-    retVal = doDeflate(env, this, addr,
-            input + inputOff, inputLen,
-            output, outputLen,
-            flush, params);
+    res = doDeflate(env, addr, input + inputOff, inputLen, output, outputLen,
+                    flush, params);
 
     (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
 
+    retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
     return retVal;
 }
 
@@ -229,19 +248,18 @@
     jbyte *input = jlong_to_ptr(inputBuffer);
     jbyte *output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
     jlong retVal;
+    jint res;
     if (output == NULL) {
         if (outputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
             JNU_ThrowOutOfMemoryError(env, 0);
         return 0L;
     }
 
-    retVal = doDeflate(env, this, addr,
-            input, inputLen,
-            output + outputOff, outputLen,
-            flush, params);
-
+    res = doDeflate(env, addr, input, inputLen, output + outputOff, outputLen,
+                    flush, params);
     (*env)->ReleasePrimitiveArrayCritical(env, outputArray, input, 0);
 
+    retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
     return retVal;
 }
 
@@ -253,11 +271,12 @@
 {
     jbyte *input = jlong_to_ptr(inputBuffer);
     jbyte *output = jlong_to_ptr(outputBuffer);
+    jlong retVal;
+    jint res;
 
-    return doDeflate(env, this, addr,
-            input, inputLen,
-            output, outputLen,
-            flush, params);
+    res = doDeflate(env, addr, input, inputLen, output, outputLen, flush, params);
+    retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
+    return retVal;
 }
 
 JNIEXPORT jint JNICALL
--- a/src/java.base/share/native/libzip/Inflater.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.base/share/native/libzip/Inflater.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -87,9 +87,8 @@
     }
 }
 
-static void doSetDictionary(JNIEnv *env, jlong addr, jbyte *buf, jint len)
+static void checkSetDictionaryResult(JNIEnv *env, jlong addr, int res)
 {
-    int res = inflateSetDictionary(jlong_to_ptr(addr), (Bytef *) buf, len);
     switch (res) {
     case Z_OK:
         break;
@@ -107,30 +106,31 @@
 Java_java_util_zip_Inflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
                                           jbyteArray b, jint off, jint len)
 {
-    jbyte *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+    jint res;
+    Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
     if (buf == NULL) /* out of memory */
         return;
-    doSetDictionary(env, addr, buf + off, len);
+    res = inflateSetDictionary(jlong_to_ptr(addr), buf + off, len);
     (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
+    checkSetDictionaryResult(env, addr, res);
 }
 
 JNIEXPORT void JNICALL
 Java_java_util_zip_Inflater_setDictionaryBuffer(JNIEnv *env, jclass cls, jlong addr,
                                           jlong bufferAddr, jint len)
 {
-    jbyte *buf = jlong_to_ptr(bufferAddr);
-    doSetDictionary(env, addr, buf, len);
+    jint res;
+    Bytef *buf = jlong_to_ptr(bufferAddr);
+    res = inflateSetDictionary(jlong_to_ptr(addr), buf, len);
+    checkSetDictionaryResult(env, addr, res);
 }
 
-static jlong doInflate(JNIEnv *env, jobject this, jlong addr,
+static jint doInflate(jlong addr,
                        jbyte *input, jint inputLen,
                        jbyte *output, jint outputLen)
 {
+    jint ret;
     z_stream *strm = jlong_to_ptr(addr);
-    jint inputUsed = 0, outputUsed = 0;
-    int finished = 0;
-    int needDict = 0;
-    int ret;
 
     strm->next_in  = (Bytef *) input;
     strm->next_out = (Bytef *) output;
@@ -138,6 +138,16 @@
     strm->avail_out = outputLen;
 
     ret = inflate(strm, Z_PARTIAL_FLUSH);
+    return ret;
+}
+
+static jlong checkInflateStatus(JNIEnv *env, jobject this, jlong addr,
+                        jint inputLen, jint outputLen, jint ret )
+{
+    z_stream *strm = jlong_to_ptr(addr);
+    jint inputUsed = 0, outputUsed = 0;
+    int finished = 0;
+    int needDict = 0;
 
     switch (ret) {
     case Z_STREAM_END:
@@ -180,6 +190,7 @@
 {
     jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
     jbyte *output;
+    jint ret;
     jlong retVal;
 
     if (input == NULL) {
@@ -195,13 +206,13 @@
         return 0L;
     }
 
-    retVal = doInflate(env, this, addr,
-            input + inputOff, inputLen,
-            output + outputOff, outputLen);
+    ret = doInflate(addr, input + inputOff, inputLen, output + outputOff,
+                    outputLen);
 
     (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
     (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
 
+    retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
     return retVal;
 }
 
@@ -212,6 +223,7 @@
 {
     jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
     jbyte *output;
+    jint ret;
     jlong retVal;
 
     if (input == NULL) {
@@ -221,11 +233,10 @@
     }
     output = jlong_to_ptr(outputBuffer);
 
-    retVal = doInflate(env, this, addr,
-            input + inputOff, inputLen,
-            output, outputLen);
+    ret = doInflate(addr, input + inputOff, inputLen, output, outputLen);
 
     (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+    retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
 
     return retVal;
 }
@@ -237,6 +248,7 @@
 {
     jbyte *input = jlong_to_ptr(inputBuffer);
     jbyte *output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
+    jint ret;
     jlong retVal;
 
     if (output == NULL) {
@@ -245,11 +257,10 @@
         return 0L;
     }
 
-    retVal = doInflate(env, this, addr,
-            input, inputLen,
-            output + outputOff, outputLen);
+    ret = doInflate(addr, input, inputLen, output  + outputOff, outputLen);
 
     (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
+    retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
 
     return retVal;
 }
@@ -261,10 +272,12 @@
 {
     jbyte *input = jlong_to_ptr(inputBuffer);
     jbyte *output = jlong_to_ptr(outputBuffer);
+    jint ret;
+    jlong retVal;
 
-    return doInflate(env, this, addr,
-            input, inputLen,
-            output, outputLen);
+    ret = doInflate(addr, input, inputLen, output, outputLen);
+    retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret);
+    return retVal;
 }
 
 JNIEXPORT jint JNICALL
--- a/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java	Wed Jun 12 10:02:49 2019 +0530
@@ -58,8 +58,8 @@
      *   9: modules, small cleanups to 1.7 and 1.8 changes
      *  10: local-variable type inference (var)
      *  11: local-variable syntax for lambda parameters
-     *  12: no changes (switch expressions in preview)
-     *  13: TBD
+     *  12: no changes (switch expressions were in preview)
+     *  13: no changes (switch expressions and text blocks in preview)
      */
 
     /**
@@ -257,8 +257,8 @@
      * followed only by characters for which {@link
      * Character#isJavaIdentifierPart(int)} returns {@code true}.
      * This pattern matches regular identifiers, keywords, restricted
-     * keywords, and the literals {@code "true"}, {@code "false"},
-     * {@code "null"}, and {@code "var"}.
+     * keywords, restricted identifiers and the literals {@code "true"},
+     * {@code "false"}, {@code "null"}.
      *
      * The method returns {@code false} for all other strings.
      *
@@ -295,7 +295,7 @@
      * for keywords, boolean literals, and the null literal.
      *
      * This method returns {@code true} for <i>restricted
-     * keywords</i> and {@code "var"}.
+     * keywords</i> and <i>restricted identifiers</i>
      *
      * @param name the string to check
      * @return {@code true} if this string is a
@@ -314,7 +314,7 @@
      * for keywords, boolean literals, and the null literal.
      *
      * This method returns {@code true} for <i>restricted
-     * keywords</i> and {@code "var"}.
+     * keywords</i> and <i>restricted identifiers</i>
      *
      * @param name the string to check
      * @param version the version to use
@@ -338,7 +338,7 @@
      * Returns whether or not {@code s} is a keyword, boolean literal,
      * or null literal in the latest source version.
      * This method returns {@code false} for <i>restricted
-     * keywords</i> and {@code "var"}.
+     * keywords</i> and <i>restricted identifiers</i>.
      *
      * @param s the string to check
      * @return {@code true} if {@code s} is a keyword, or boolean
@@ -355,7 +355,7 @@
      * Returns whether or not {@code s} is a keyword, boolean literal,
      * or null literal in the given source version.
      * This method returns {@code false} for <i>restricted
-     * keywords</i> and {@code "var"}.
+     * keywords</i> and <i>restricted identifiers</i>.
      *
      * @param s the string to check
      * @param version the version to use
--- a/src/java.sql/share/classes/java/sql/package-info.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.sql/share/classes/java/sql/package-info.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -336,8 +336,7 @@
  *   <li><a href="http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html">
  *           Lesson:JDBC Basics(The Javaxx Tutorials &gt; JDBC&trade; Database Access)</a>
  *
- *  <li><a href="http://www.oracle.com/technetwork/java/index-142838.html">
- *           <i>JDBC&trade; API Tutorial and Reference, Third Edition</i></a>
+ *  <li>&ldquo;<i>JDBC&trade; API Tutorial and Reference, Third Edition</i>&rdquo;
  * </ul>
  */
 package java.sql;
--- a/src/java.sql/share/classes/javax/sql/package-info.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/java.sql/share/classes/javax/sql/package-info.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  * <p>
  * This code is free software; you can redistribute it and/or modify it
@@ -287,8 +287,7 @@
  * package:
  *
  * <ul>
- * <li><a href="http://www.oracle.com/technetwork/java/index-142838.html">
- * <i>JDBC&#8482;API Tutorial and Reference, Third Edition</i></a>
+ * <li>&ldquo;<i>JDBC&#8482;API Tutorial and Reference, Third Edition</i>&rdquo;
  * </ul>
  */
 package javax.sql;
--- a/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MetadataBuilder.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MetadataBuilder.java	Wed Jun 12 10:02:49 2019 +0530
@@ -25,16 +25,20 @@
 
 package jdk.tools.jaotc;
 
+import static jdk.tools.jaotc.AOTCompiledClass.getType;
+import static jdk.tools.jaotc.AOTCompiledClass.metadataName;
+
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.List;
 
+import org.graalvm.compiler.code.CompilationResult;
+import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
+
 import jdk.tools.jaotc.binformat.BinaryContainer;
 import jdk.tools.jaotc.binformat.ByteContainer;
 import jdk.tools.jaotc.binformat.GotSymbol;
 import jdk.tools.jaotc.utils.NativeOrderOutputStream;
-import org.graalvm.compiler.code.CompilationResult;
-import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
-
 import jdk.vm.ci.code.StackSlot;
 import jdk.vm.ci.code.site.DataPatch;
 import jdk.vm.ci.code.site.Infopoint;
@@ -42,9 +46,6 @@
 import jdk.vm.ci.hotspot.HotSpotCompiledCode;
 import jdk.vm.ci.hotspot.HotSpotMetaData;
 
-import static jdk.tools.jaotc.AOTCompiledClass.getType;
-import static jdk.tools.jaotc.AOTCompiledClass.metadataName;
-
 final class MetadataBuilder {
 
     private final DataBuilder dataBuilder;
@@ -81,6 +82,12 @@
         HotSpotGraalRuntimeProvider runtime = dataBuilder.getBackend().getRuntime();
         ByteContainer methodMetadataContainer = binaryContainer.getMethodMetadataContainer();
 
+        Method implicitExceptionsMethod = null;
+        try {
+            implicitExceptionsMethod = HotSpotMetaData.class.getDeclaredMethod("implicitExceptionBytes");
+        } catch (NoSuchMethodException e) {
+        }
+
         // For each of the compiled java methods, create records holding information about them.
         for (CompiledMethodInfo methodInfo : compiledClass.getCompiledMethods()) {
             // Get the current offset in the methodmetadata container.
@@ -141,6 +148,11 @@
                 NativeOrderOutputStream.PatchableInt scopeOffset = metadataStream.patchableInt();
                 NativeOrderOutputStream.PatchableInt relocationOffset = metadataStream.patchableInt();
                 NativeOrderOutputStream.PatchableInt exceptionOffset = metadataStream.patchableInt();
+                NativeOrderOutputStream.PatchableInt implictTableOFfset = null;
+
+                if (implicitExceptionsMethod != null) {
+                    implictTableOFfset = metadataStream.patchableInt();
+                }
                 NativeOrderOutputStream.PatchableInt oopMapOffset = metadataStream.patchableInt();
                 metadataStream.align(8);
 
@@ -156,6 +168,12 @@
                 exceptionOffset.set(metadataStream.position());
                 metadataStream.put(metaData.exceptionBytes()).align(8);
 
+                if (implicitExceptionsMethod != null) {
+                    implictTableOFfset.set(metadataStream.position());
+                    byte[] data = (byte[]) implicitExceptionsMethod.invoke(metaData);
+                    metadataStream.put(data).align(8);
+                }
+
                 // oopmaps should be last
                 oopMapOffset.set(metadataStream.position());
                 metadataStream.put(oopMapInfo).align(8);
--- a/src/jdk.compiler/share/classes/com/sun/source/tree/BreakTree.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/source/tree/BreakTree.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,8 +35,6 @@
  *   break;
  *
  *   break <em>label</em> ;
- *
- *   break <em>expression</em> ;
  * </pre>
  *
  * @jls 14.15 The break Statement
@@ -52,17 +50,4 @@
      */
     Name getLabel();
 
-    /**
-     * Returns the expression for this {@code break} statement.
-     *
-     * @return the expression
-     * @since 12
-     *
-     * @deprecated This method is modeling value breaks, which are part of
-     * a preview feature and may be removed if the preview feature
-     * is removed.
-     *
-     */
-    @Deprecated(forRemoval=true, since="12")
-    ExpressionTree getValue();
 }
--- a/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -656,7 +656,21 @@
          * An implementation-reserved node. This is the not the node
          * you are looking for.
          */
-        OTHER(null);
+        OTHER(null),
+
+        /**
+         * Used for instances of {@link YieldTree}.
+         *
+         * @since 13
+         *
+         * @deprecated
+         * This enum constant is modeling yield statement,
+         * which are part of a preview feature and may be removed
+         * if the preview feature is removed.
+         */
+        @Deprecated(forRemoval=true, since="13")
+        @SuppressWarnings("removal")
+        YIELD(YieldTree.class);
 
 
         Kind(Class<? extends Tree> intf) {
--- a/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -555,4 +555,20 @@
      * @return a result value
      */
     R visitOther(Tree node, P p);
+
+    /**
+     * Visits a YieldTree node.
+     * @param node the node being visited
+     * @param p a parameter value
+     * @return a result value
+     * @since 13
+     *
+     * @deprecated
+     * This method is modeling yield statement,
+     * which are part of a preview feature and may be removed
+     * if the preview feature is removed.
+     */
+    @Deprecated(forRemoval=true, since="13")
+    @SuppressWarnings("removal")
+    R visitYield(YieldTree node, P p);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.compiler/share/classes/com/sun/source/tree/YieldTree.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.source.tree;
+
+/**
+ * A tree node for a {@code yield} statement.
+ *
+ * For example:
+ * <pre>
+ *   yield <em>expression</em> ;
+ * </pre>
+ *
+ * @jls section TODO
+ *
+ * @since 13
+ *
+ * @deprecated This class is modeling yield from switch expressions,
+ * which are part of a preview feature and may be removed if
+ * the preview feature is removed.
+ */
+@Deprecated(forRemoval=true, since="13")
+public interface YieldTree extends StatementTree {
+
+    /**
+     * Returns the expression for this {@code yield} statement.
+     *
+     * @return the expression
+     */
+    ExpressionTree getValue();
+}
--- a/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -782,4 +782,18 @@
     public R visitOther(Tree node, P p) {
         return defaultAction(node, p);
     }
+
+    /**
+     * {@inheritDoc} This implementation calls {@code defaultAction}.
+     *
+     * @param node {@inheritDoc}
+     * @param p {@inheritDoc}
+     * @return  the result of {@code defaultAction}
+     */
+    @Override
+    @Deprecated(forRemoval=true, since="13")
+    @SuppressWarnings("removal")
+    public R visitYield(YieldTree node, P p) {
+        return defaultAction(node, p);
+    }
 }
--- a/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -467,9 +467,8 @@
      * @return the result of scanning
      */
     @Override
-    @SuppressWarnings("removal")
     public R visitBreak(BreakTree node, P p) {
-        return scan(node.getValue(), p);
+        return null;
     }
 
     /**
@@ -935,4 +934,23 @@
     public R visitErroneous(ErroneousTree node, P p) {
         return null;
     }
+
+    /**
+     * {@inheritDoc} This implementation returns {@code null}.
+     *
+     * @param node  {@inheritDoc}
+     * @param p  {@inheritDoc}
+     * @return the result of scanning
+     *
+     * @deprecated
+     * This method is modeling switch expressions,
+     * which are part of a preview feature and may be removed
+     * if the preview feature is removed.
+     */
+    @Override
+    @Deprecated(forRemoval=true, since="13")
+    @SuppressWarnings("removal")
+    public R visitYield(YieldTree node, P p) {
+        return scan(node.getValue(), p);
+    }
 }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java	Wed Jun 12 10:02:49 2019 +0530
@@ -71,7 +71,7 @@
         HIDDEN(Category.RESOLUTION_TARGET),                            // not overloaded   non-target
         STATICERR(Category.RESOLUTION_TARGET),                         // overloaded?      target
         MISSING_ENCL(Category.RESOLUTION),                             // not overloaded   non-target
-        BAD_VAR(Category.RESOLUTION),                                  // not overloaded   non-target
+        BAD_RESTRICTED_TYPE(Category.RESOLUTION),                      // not overloaded   non-target
         ABSENT_VAR(Category.RESOLUTION_TARGET, KindName.VAR),          // not overloaded   non-target
         WRONG_MTHS(Category.RESOLUTION_TARGET, KindName.METHOD),       // overloaded       target
         WRONG_MTH(Category.RESOLUTION_TARGET, KindName.METHOD),        // not overloaded   target
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -84,10 +84,13 @@
     /** 1.11 local-variable syntax for lambda parameters */
     JDK11("11"),
 
-    /** 12 covers the to be determined language features that will be added in JDK 12. */
+    /** 12, no language features; switch expression were in preview */
     JDK12("12"),
 
-    /** 13 covers the to be determined language features that will be added in JDK 13. */
+    /**
+     * 13, no language features; text blocks and revised switch
+     * expressions in preview
+     */
     JDK13("13");
 
     private static final Context.Key<Source> sourceKey = new Context.Key<>();
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ArgumentAttr.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ArgumentAttr.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,6 @@
 import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase;
 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
 import com.sun.tools.javac.tree.JCTree;
-import com.sun.tools.javac.tree.JCTree.JCBreak;
 import com.sun.tools.javac.tree.JCTree.JCConditional;
 import com.sun.tools.javac.tree.JCTree.JCExpression;
 import com.sun.tools.javac.tree.JCTree.JCLambda;
@@ -77,6 +76,7 @@
 import static com.sun.tools.javac.code.TypeTag.FORALL;
 import static com.sun.tools.javac.code.TypeTag.METHOD;
 import static com.sun.tools.javac.code.TypeTag.VOID;
+import com.sun.tools.javac.tree.JCTree.JCYield;
 
 /**
  * This class performs attribution of method/constructor arguments when target-typing is enabled
@@ -468,7 +468,7 @@
      */
     class SwitchExpressionType extends ArgumentType<JCSwitchExpression> {
         /** List of break expressions (lazily populated). */
-        Optional<List<JCBreak>> breakExpressions = Optional.empty();
+        Optional<List<JCYield>> yieldExpressions = Optional.empty();
 
         SwitchExpressionType(JCExpression tree, Env<AttrContext> env, JCSwitchExpression speculativeCond) {
             this(tree, env, speculativeCond, new HashMap<>());
@@ -487,7 +487,7 @@
                 return attr.types.createErrorType(resultInfo.pt);
             } else {
                 //poly
-                for (JCBreak brk : breakExpressions()) {
+                for (JCYield brk : yieldExpressions()) {
                     checkSpeculative(brk.value, brk.value.type, resultInfo);
                 }
                 return localInfo.pt;
@@ -495,19 +495,20 @@
         }
 
         /** Compute return expressions (if needed). */
-        List<JCBreak> breakExpressions() {
-            return breakExpressions.orElseGet(() -> {
-                final List<JCBreak> res;
-                ListBuffer<JCBreak> buf = new ListBuffer<>();
+        List<JCYield> yieldExpressions() {
+            return yieldExpressions.orElseGet(() -> {
+                final List<JCYield> res;
+                ListBuffer<JCYield> buf = new ListBuffer<>();
                 new SwitchExpressionScanner() {
                     @Override
-                    public void visitBreak(JCBreak tree) {
+                    public void visitYield(JCYield tree) {
                         if (tree.target == speculativeTree)
                             buf.add(tree);
+                        super.visitYield(tree);
                     }
                 }.scan(speculativeTree.cases);
                 res = buf.toList();
-                breakExpressions = Optional.of(res);
+                yieldExpressions = Optional.of(res);
                 return res;
             });
         }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Wed Jun 12 10:02:49 2019 +0530
@@ -77,6 +77,8 @@
 import com.sun.tools.javac.comp.Analyzer.AnalyzerMode;
 import static com.sun.tools.javac.tree.JCTree.Tag.*;
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
+import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler;
+import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
 
 /** This is the main context-dependent analysis phase in GJC. It
  *  encompasses name resolution, type checking and constant folding as
@@ -358,7 +360,7 @@
                 Name name = (Name)node.getIdentifier();
                 if (site.kind == PCK) {
                     env.toplevel.packge = (PackageSymbol)site;
-                    return rs.findIdentInPackage(env, (TypeSymbol)site, name,
+                    return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
                             KindSelector.TYP_PCK);
                 } else {
                     env.enclClass.sym = (ClassSymbol)site;
@@ -368,7 +370,7 @@
 
             @Override @DefinedBy(Api.COMPILER_TREE)
             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
-                return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
+                return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
             }
         }
 
@@ -1425,16 +1427,16 @@
         ListBuffer<Type> caseTypes = new ListBuffer<>();
 
         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
-            caseEnv.info.breakResult = condInfo;
+            caseEnv.info.yieldResult = condInfo;
             attribStats(c.stats, caseEnv);
             new TreeScanner() {
                 @Override
-                public void visitBreak(JCBreak brk) {
+                public void visitYield(JCYield brk) {
                     if (brk.target == tree) {
                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
                     }
-                    super.visitBreak(brk);
+                    super.visitYield(brk);
                 }
 
                 @Override public void visitClassDef(JCClassDecl tree) {}
@@ -1864,67 +1866,19 @@
     }
 
     public void visitBreak(JCBreak tree) {
-        if (env.info.breakResult != null) {
-            if (tree.value == null) {
-                tree.target = findJumpTarget(tree.pos(), tree.getTag(), null, env);
-                if (tree.target.hasTag(SWITCH_EXPRESSION)) {
-                    log.error(tree.pos(), Errors.BreakMissingValue);
-                }
-            } else {
-                if (env.info.breakResult.pt.hasTag(VOID)) {
-                    //can happen?
-                    env.info.breakResult.checkContext.report(tree.value.pos(),
-                              diags.fragment(Fragments.UnexpectedRetVal));
-                }
-                boolean attribute = true;
-                if (tree.value.hasTag(IDENT)) {
-                    //disambiguate break <LABEL> and break <ident-as-an-expression>:
-                    Name label = ((JCIdent) tree.value).name;
-                    Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tree.getTag(), label, env);
-
-                    if (jumpTarget.fst != null) {
-                        JCTree speculative = deferredAttr.attribSpeculative(tree.value, env, unknownExprInfo);
-                        if (!speculative.type.hasTag(ERROR)) {
-                            log.error(tree.pos(), Errors.BreakAmbiguousTarget(label));
-                            if (jumpTarget.snd == null) {
-                                tree.target = jumpTarget.fst;
-                                attribute = false;
-                            } else {
-                                //nothing
-                            }
-                        } else {
-                            if (jumpTarget.snd != null) {
-                                log.error(tree.pos(), jumpTarget.snd);
-                            }
-                            tree.target = jumpTarget.fst;
-                            attribute = false;
-                        }
-                    }
-                }
-                if (attribute) {
-                    attribTree(tree.value, env, env.info.breakResult);
-                    JCTree immediateTarget = findJumpTarget(tree.pos(), tree.getTag(), null, env);
-                    if (immediateTarget.getTag() != SWITCH_EXPRESSION) {
-                        log.error(tree.pos(), Errors.BreakExprNotImmediate(immediateTarget.getTag()));
-                        Env<AttrContext> env1 = env;
-                        while (env1 != null && env1.tree.getTag() != SWITCH_EXPRESSION) {
-                            env1 = env1.next;
-                        }
-                        Assert.checkNonNull(env1);
-                        tree.target = env1.tree;
-                    } else {
-                        tree.target = immediateTarget;
-                    }
-                }
-            }
+        tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
+        result = null;
+    }
+
+    public void visitYield(JCYield tree) {
+        if (env.info.yieldResult != null) {
+            attribTree(tree.value, env, env.info.yieldResult);
+            tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
         } else {
-            if (tree.value == null || tree.value.hasTag(IDENT)) {
-                Name label = tree.value != null ? ((JCIdent) tree.value).name : null;
-                tree.target = findJumpTarget(tree.pos(), tree.getTag(), label, env);
-            } else {
-                log.error(tree.pos(), Errors.BreakComplexValueNoSwitchExpression);
-                attribTree(tree.value, env, unknownExprInfo);
-            }
+            log.error(tree.pos(), tree.value.hasTag(PARENS)
+                    ? Errors.NoSwitchExpressionQualify
+                    : Errors.NoSwitchExpression);
+            attribTree(tree.value, env, unknownExprInfo);
         }
         result = null;
     }
@@ -1934,8 +1888,8 @@
         result = null;
     }
     //where
-        /** Return the target of a break or continue statement, if it exists,
-         *  report an error if not.
+        /** Return the target of a break, continue or yield statement,
+         *  if it exists, report an error if not.
          *  Note: The target of a labelled break or continue is the
          *  (non-labelled) statement tree referred to by the label,
          *  not the tree representing the labelled statement itself.
@@ -2009,12 +1963,10 @@
                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
                         break;
                     case SWITCH_EXPRESSION:
-                        if (tag == BREAK) {
-                            if (label == null) {
-                                return Pair.of(env1.tree, null);
-                            } else {
-                                pendingError = Errors.BreakOutsideSwitchExpression;
-                            }
+                        if (tag == YIELD) {
+                            return Pair.of(env1.tree, null);
+                        } else if (tag == BREAK) {
+                            pendingError = Errors.BreakOutsideSwitchExpression;
                         } else {
                             pendingError = Errors.ContinueOutsideSwitchExpression;
                         }
@@ -2029,6 +1981,8 @@
             }
             if (label != null)
                 return Pair.of(null, Errors.UndefLabel(label));
+            else if (pendingError != null)
+                return Pair.of(null, pendingError);
             else if (tag == CONTINUE)
                 return Pair.of(null, Errors.ContOutsideLoop);
             else
@@ -2040,7 +1994,7 @@
         // nested within than the enclosing class.
         if (env.info.returnResult == null) {
             log.error(tree.pos(), Errors.RetOutsideMeth);
-        } else if (env.info.breakResult != null) {
+        } else if (env.info.yieldResult != null) {
             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
         } else {
             // Attribute return expression, if it exists, and check that
@@ -3136,7 +3090,7 @@
             } else {
                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
             }
-            lambdaEnv.info.breakResult = null;
+            lambdaEnv.info.yieldResult = null;
             return lambdaEnv;
         }
 
@@ -3916,7 +3870,7 @@
             switch (site.getTag()) {
             case PACKAGE:
                 return rs.accessBase(
-                    rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
+                    rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
                     pos, location, site, name, true);
             case ARRAY:
             case CLASS:
@@ -3931,7 +3885,7 @@
                     return syms.getClassField(site, types);
                 } else {
                     // We are seeing a plain identifier as selector.
-                    Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
+                    Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
                         sym = rs.accessBase(sym, pos, location, site, name, true);
                     return sym;
                 }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrContext.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrContext.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -101,10 +101,10 @@
      */
     Attr.ResultInfo returnResult = null;
 
-    /** ResultInfo to be used for attributing 'break' statement expressions
+    /** ResultInfo to be used for attributing 'yield' statement expressions
      * (set by Attr.visitSwitchExpression)
      */
-    Attr.ResultInfo breakResult = null;
+    Attr.ResultInfo yieldResult = null;
 
     /** Symbol corresponding to the site of a qualified default super call
      */
@@ -129,7 +129,7 @@
         info.lint = lint;
         info.enclVar = enclVar;
         info.returnResult = returnResult;
-        info.breakResult = breakResult;
+        info.yieldResult = yieldResult;
         info.defaultSuperCallSite = defaultSuperCallSite;
         info.isSerializable = isSerializable;
         info.isLambda = isLambda;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1161,7 +1161,7 @@
 
         SwitchExpressionScanner() {
             super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
-                    FORLOOP, IF, BREAK, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
+                    FORLOOP, IF, SYNCHRONIZED, SWITCH, TRY, WHILELOOP, YIELD));
         }
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -314,6 +314,12 @@
                 JCTree getTarget(JCTree tree) {
                     return ((JCContinue)tree).target;
                 }
+            },
+            YIELD(JCTree.Tag.YIELD) {
+                @Override
+                JCTree getTarget(JCTree tree) {
+                    return ((JCYield)tree).target;
+                }
             };
 
             final JCTree.Tag treeTag;
@@ -386,6 +392,11 @@
             return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
         }
 
+        /** Resolve all yields of this statement. */
+        Liveness resolveYields(JCTree tree, ListBuffer<PendingExit> oldPendingExits) {
+            return resolveJump(tree, oldPendingExits, JumpKind.YIELD);
+        }
+
         @Override
         public void scan(JCTree tree) {
             if (tree != null && (
@@ -400,9 +411,15 @@
         }
 
         protected void scanSyntheticBreak(TreeMaker make, JCTree swtch) {
-            JCBreak brk = make.at(Position.NOPOS).Break(null);
-            brk.target = swtch;
-            scan(brk);
+            if (swtch.hasTag(SWITCH_EXPRESSION)) {
+                JCYield brk = make.at(Position.NOPOS).Yield(null);
+                brk.target = swtch;
+                scan(brk);
+            } else {
+                JCBreak brk = make.at(Position.NOPOS).Break(null);
+                brk.target = swtch;
+                scan(brk);
+            }
         }
     }
 
@@ -517,7 +534,8 @@
                 while (exits.nonEmpty()) {
                     PendingExit exit = exits.head;
                     exits = exits.tail;
-                    Assert.check(exit.tree.hasTag(RETURN));
+                    Assert.check(exit.tree.hasTag(RETURN) ||
+                                    log.hasErrorOn(exit.tree.pos()));
                 }
             } finally {
                 lint = lintPrev;
@@ -677,7 +695,7 @@
                 log.error(tree, Errors.NotExhaustive);
             }
             alive = prevAlive;
-            alive = alive.or(resolveBreaks(tree, prevPendingExits));
+            alive = alive.or(resolveYields(tree, prevPendingExits));
         }
 
         public void visitTry(JCTry tree) {
@@ -745,8 +763,12 @@
         }
 
         public void visitBreak(JCBreak tree) {
-            if (tree.isValueBreak())
-                scan(tree.value);
+            recordExit(new PendingExit(tree));
+        }
+
+        @Override
+        public void visitYield(JCYield tree) {
+            scan(tree.value);
             recordExit(new PendingExit(tree));
         }
 
@@ -1032,7 +1054,8 @@
                     PendingExit exit = exits.head;
                     exits = exits.tail;
                     if (!(exit instanceof ThrownPendingExit)) {
-                        Assert.check(exit.tree.hasTag(RETURN));
+                        Assert.check(exit.tree.hasTag(RETURN) ||
+                                         log.hasErrorOn(exit.tree.pos()));
                     } else {
                         // uncaught throws will be reported later
                         pendingExits.append(exit);
@@ -1126,7 +1149,11 @@
                 scan(c.pats);
                 scan(c.stats);
             }
-            resolveBreaks(tree, prevPendingExits);
+            if (tree.hasTag(SWITCH_EXPRESSION)) {
+                resolveYields(tree, prevPendingExits);
+            } else {
+                resolveBreaks(tree, prevPendingExits);
+            }
         }
 
         public void visitTry(JCTry tree) {
@@ -1267,8 +1294,11 @@
             }
 
         public void visitBreak(JCBreak tree) {
-            if (tree.isValueBreak())
-                scan(tree.value);
+            recordExit(new PendingExit(tree));
+        }
+
+        public void visitYield(JCYield tree) {
+            scan(tree.value);
             recordExit(new PendingExit(tree));
         }
 
@@ -1357,7 +1387,8 @@
                     PendingExit exit = exits.head;
                     exits = exits.tail;
                     if (!(exit instanceof ThrownPendingExit)) {
-                        Assert.check(exit.tree.hasTag(RETURN));
+                        Assert.check(exit.tree.hasTag(RETURN) ||
+                                        log.hasErrorOn(exit.tree.pos()));
                     } else {
                         // uncaught throws will be reported later
                         pendingExits.append(exit);
@@ -1977,7 +2008,9 @@
                     while (exits.nonEmpty()) {
                         PendingExit exit = exits.head;
                         exits = exits.tail;
-                        Assert.check(exit.tree.hasTag(RETURN), exit.tree);
+                        Assert.check(exit.tree.hasTag(RETURN) ||
+                                         log.hasErrorOn(exit.tree.pos()),
+                                     exit.tree);
                         if (isInitialConstructor) {
                             Assert.check(exit instanceof AssignPendingExit);
                             inits.assign(((AssignPendingExit) exit).exit_inits);
@@ -2232,7 +2265,11 @@
                     inits.andSet(initsSwitch);
                 }
             }
-            resolveBreaks(tree, prevPendingExits);
+            if (tree.hasTag(SWITCH_EXPRESSION)) {
+                resolveYields(tree, prevPendingExits);
+            } else {
+                resolveBreaks(tree, prevPendingExits);
+            }
             nextadr = nextadrPrev;
         }
         // where
@@ -2397,35 +2434,37 @@
 
         @Override
         public void visitBreak(JCBreak tree) {
-            if (tree.isValueBreak()) {
-                if (tree.target.hasTag(SWITCH_EXPRESSION)) {
-                    JCSwitchExpression expr = (JCSwitchExpression) tree.target;
-                    if (expr.type.hasTag(BOOLEAN)) {
-                        scanCond(tree.value);
-                        Bits initsAfterBreakWhenTrue = new Bits(initsWhenTrue);
-                        Bits initsAfterBreakWhenFalse = new Bits(initsWhenFalse);
-                        Bits uninitsAfterBreakWhenTrue = new Bits(uninitsWhenTrue);
-                        Bits uninitsAfterBreakWhenFalse = new Bits(uninitsWhenFalse);
-                        PendingExit exit = new PendingExit(tree) {
-                            @Override
-                            void resolveJump() {
-                                if (!inits.isReset()) {
-                                    split(true);
-                                }
-                                initsWhenTrue.andSet(initsAfterBreakWhenTrue);
-                                initsWhenFalse.andSet(initsAfterBreakWhenFalse);
-                                uninitsWhenTrue.andSet(uninitsAfterBreakWhenTrue);
-                                uninitsWhenFalse.andSet(uninitsAfterBreakWhenFalse);
-                            }
-                        };
-                        merge();
-                        recordExit(exit);
-                        return ;
+            recordExit(new AssignPendingExit(tree, inits, uninits));
+        }
+
+        @Override
+        public void visitYield(JCYield tree) {
+            JCSwitchExpression expr = (JCSwitchExpression) tree.target;
+            if (expr != null && expr.type.hasTag(BOOLEAN)) {
+                scanCond(tree.value);
+                Bits initsAfterBreakWhenTrue = new Bits(initsWhenTrue);
+                Bits initsAfterBreakWhenFalse = new Bits(initsWhenFalse);
+                Bits uninitsAfterBreakWhenTrue = new Bits(uninitsWhenTrue);
+                Bits uninitsAfterBreakWhenFalse = new Bits(uninitsWhenFalse);
+                PendingExit exit = new PendingExit(tree) {
+                    @Override
+                    void resolveJump() {
+                        if (!inits.isReset()) {
+                            split(true);
+                        }
+                        initsWhenTrue.andSet(initsAfterBreakWhenTrue);
+                        initsWhenFalse.andSet(initsAfterBreakWhenFalse);
+                        uninitsWhenTrue.andSet(uninitsAfterBreakWhenTrue);
+                        uninitsWhenFalse.andSet(uninitsAfterBreakWhenFalse);
                     }
-                }
+                };
+                merge();
+                recordExit(exit);
+                return ;
+            } else {
                 scan(tree.value);
+                recordExit(new AssignPendingExit(tree, inits, uninits));
             }
-            recordExit(new AssignPendingExit(tree, inits, uninits));
         }
 
         @Override
@@ -2788,9 +2827,8 @@
         }
 
         @Override
-        public void visitBreak(JCBreak tree) {
-            if (tree.isValueBreak())
-                scan(tree.value);
+        public void visitYield(JCYield tree) {
+            scan(tree.value);
         }
 
         public void visitModuleDef(JCModuleDecl tree) {
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -272,9 +272,8 @@
         }
 
         @Override
-        public void visitBreak(JCBreak tree) {
-            if (tree.isValueBreak())
-                scan(tree.value);
+        public void visitYield(JCYield tree) {
+            scan(tree.value);
         }
 
     }
@@ -1887,7 +1886,7 @@
             ClassSymbol c = types.boxedClass(type);
             Symbol typeSym =
                 rs.accessBase(
-                    rs.findIdentInType(attrEnv, c.type, names.TYPE, KindSelector.VAR),
+                    rs.findIdentInType(pos, attrEnv, c.type, names.TYPE, KindSelector.VAR),
                     pos, c.type, names.TYPE, true);
             if (typeSym.kind == VAR)
                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
@@ -3224,6 +3223,11 @@
                     if (tree.target == src)
                         tree.target = dest;
                 }
+                public void visitYield(JCYield tree) {
+                    if (tree.target == src)
+                        tree.target = dest;
+                    scan(tree.value);
+                }
                 public void visitContinue(JCContinue tree) {
                     if (tree.target == src)
                         tree.target = dest;
@@ -3676,9 +3680,12 @@
 
     @Override
     public void visitBreak(JCBreak tree) {
-        if (tree.isValueBreak()) {
-            tree.value = translate(tree.value, tree.target.type);
-        }
+        result = tree;
+    }
+
+    @Override
+    public void visitYield(JCYield tree) {
+        tree.value = translate(tree.value, tree.target.type);
         result = tree;
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java	Wed Jun 12 10:02:49 2019 +0530
@@ -245,7 +245,7 @@
                                                              tree.sym.type.getReturnType());
         }
         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
-        localEnv.info.breakResult = null;
+        localEnv.info.yieldResult = null;
         return localEnv;
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Wed Jun 12 10:02:49 2019 +0530
@@ -43,6 +43,7 @@
 import com.sun.tools.javac.main.Option;
 import com.sun.tools.javac.resources.CompilerProperties.Errors;
 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
+import com.sun.tools.javac.resources.CompilerProperties.Warnings;
 import com.sun.tools.javac.tree.*;
 import com.sun.tools.javac.tree.JCTree.*;
 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
@@ -52,6 +53,7 @@
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
+import com.sun.tools.javac.util.JCDiagnostic.Warning;
 
 import java.util.Arrays;
 import java.util.Collection;
@@ -63,6 +65,7 @@
 import java.util.Set;
 import java.util.function.BiFunction;
 import java.util.function.BiPredicate;
+import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.stream.Stream;
@@ -105,6 +108,7 @@
     public final boolean checkVarargsAccessAfterResolution;
     private final boolean compactMethodDiags;
     private final boolean allowLocalVariableTypeInference;
+    private final boolean allowYieldStatement;
     final EnumSet<VerboseResolutionMode> verboseResolutionMode;
 
     WriteableScope polymorphicSignatureScope;
@@ -128,6 +132,7 @@
         moduleFinder = ModuleFinder.instance(context);
         types = Types.instance(context);
         diags = JCDiagnostic.Factory.instance(context);
+        Preview preview = Preview.instance(context);
         Source source = Source.instance(context);
         Options options = Options.instance(context);
         compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
@@ -136,6 +141,8 @@
         Target target = Target.instance(context);
         allowFunctionalInterfaceMostSpecific = Feature.FUNCTIONAL_INTERFACE_MOST_SPECIFIC.allowedInSource(source);
         allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source);
+        allowYieldStatement = (!preview.isPreview(Feature.SWITCH_EXPRESSION) || preview.isEnabled()) &&
+                Feature.SWITCH_EXPRESSION.allowedInSource(source);
         checkVarargsAccessAfterResolution =
                 Feature.POST_APPLICABILITY_VARARGS_ACCESS_CHECK.allowedInSource(source);
         polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
@@ -2330,13 +2337,15 @@
     }
 
     /** Find an unqualified identifier which matches a specified kind set.
+     *  @param pos       position on which report warnings, if any;
+     *                   null warnings should not be reported
      *  @param env       The current environment.
      *  @param name      The identifier's name.
      *  @param kind      Indicates the possible symbol kinds
      *                   (a subset of VAL, TYP, PCK).
      */
-    Symbol findIdent(Env<AttrContext> env, Name name, KindSelector kind) {
-        return checkVarType(findIdentInternal(env, name, kind), name);
+    Symbol findIdent(DiagnosticPosition pos, Env<AttrContext> env, Name name, KindSelector kind) {
+        return checkRestrictedType(pos, findIdentInternal(env, name, kind), name);
     }
 
     Symbol findIdentInternal(Env<AttrContext> env, Name name, KindSelector kind) {
@@ -2362,14 +2371,17 @@
     }
 
     /** Find an identifier in a package which matches a specified kind set.
+     *  @param pos       position on which report warnings, if any;
+     *                   null warnings should not be reported
      *  @param env       The current environment.
      *  @param name      The identifier's name.
      *  @param kind      Indicates the possible symbol kinds
      *                   (a nonempty subset of TYP, PCK).
      */
-    Symbol findIdentInPackage(Env<AttrContext> env, TypeSymbol pck,
+    Symbol findIdentInPackage(DiagnosticPosition pos,
+                              Env<AttrContext> env, TypeSymbol pck,
                               Name name, KindSelector kind) {
-        return checkVarType(findIdentInPackageInternal(env, pck, name, kind), name);
+        return checkRestrictedType(pos, findIdentInPackageInternal(env, pck, name, kind), name);
     }
 
     Symbol findIdentInPackageInternal(Env<AttrContext> env, TypeSymbol pck,
@@ -2395,15 +2407,18 @@
     }
 
     /** Find an identifier among the members of a given type `site'.
+     *  @param pos       position on which report warnings, if any;
+     *                   null warnings should not be reported
      *  @param env       The current environment.
      *  @param site      The type containing the symbol to be found.
      *  @param name      The identifier's name.
      *  @param kind      Indicates the possible symbol kinds
      *                   (a subset of VAL, TYP).
      */
-    Symbol findIdentInType(Env<AttrContext> env, Type site,
+    Symbol findIdentInType(DiagnosticPosition pos,
+                           Env<AttrContext> env, Type site,
                            Name name, KindSelector kind) {
-        return checkVarType(findIdentInTypeInternal(env, site, name, kind), name);
+        return checkRestrictedType(pos, findIdentInTypeInternal(env, site, name, kind), name);
     }
 
     Symbol findIdentInTypeInternal(Env<AttrContext> env, Type site,
@@ -2424,10 +2439,17 @@
         return bestSoFar;
     }
 
-    private Symbol checkVarType(Symbol bestSoFar, Name name) {
-        if (allowLocalVariableTypeInference && name.equals(names.var) &&
-                (bestSoFar.kind == TYP || bestSoFar.kind == ABSENT_TYP)) {
-            bestSoFar = new BadVarTypeError();
+    private Symbol checkRestrictedType(DiagnosticPosition pos, Symbol bestSoFar, Name name) {
+        if (bestSoFar.kind == TYP || bestSoFar.kind == ABSENT_TYP) {
+            if (allowLocalVariableTypeInference && name.equals(names.var)) {
+                bestSoFar = new BadRestrictedTypeError(names.var);
+            } else if (name.equals(names.yield)) {
+                if (allowYieldStatement) {
+                    bestSoFar = new BadRestrictedTypeError(names.yield);
+                } else if (pos != null) {
+                    log.warning(pos, Warnings.IllegalRefToRestrictedType(names.yield));
+                }
+            }
         }
         return bestSoFar;
     }
@@ -2597,7 +2619,7 @@
     Symbol resolveIdent(DiagnosticPosition pos, Env<AttrContext> env,
                         Name name, KindSelector kind) {
         return accessBase(
-            findIdent(env, name, kind),
+            findIdent(pos, env, name, kind),
             pos, env.enclClass.sym.type, name, false);
     }
 
@@ -3833,14 +3855,16 @@
         }
     }
 
-    class BadVarTypeError extends ResolveError {
-        BadVarTypeError() {
-            super(Kind.BAD_VAR, "bad var use");
+    class BadRestrictedTypeError extends ResolveError {
+        private final Name typeName;
+        BadRestrictedTypeError(Name typeName) {
+            super(Kind.BAD_RESTRICTED_TYPE, "bad var use");
+            this.typeName = typeName;
         }
 
         @Override
         JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes) {
-            return diags.create(dkind, log.currentSource(), pos, "illegal.ref.to.var.type");
+            return diags.create(dkind, log.currentSource(), pos, "illegal.ref.to.restricted.type", typeName);
         }
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransTypes.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -620,11 +620,14 @@
 
     @Override
     public void visitBreak(JCBreak tree) {
-        if (tree.isValueBreak()) {
-            tree.value = translate(tree.value, erasure(tree.value.type));
-            tree.value.type = erasure(tree.value.type);
-            tree.value = retype(tree.value, tree.value.type, pt);
-        }
+        result = tree;
+    }
+
+    @Override
+    public void visitYield(JCYield tree) {
+        tree.value = translate(tree.value, erasure(tree.value.type));
+        tree.value.type = erasure(tree.value.type);
+        tree.value = retype(tree.value, tree.value.type, pt);
         result = tree;
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java	Wed Jun 12 10:02:49 2019 +0530
@@ -71,6 +71,7 @@
 import com.sun.tools.javac.tree.JCTree.JCRequires;
 import com.sun.tools.javac.tree.JCTree.JCReturn;
 import com.sun.tools.javac.tree.JCTree.JCSwitch;
+import com.sun.tools.javac.tree.JCTree.JCSwitchExpression;
 import com.sun.tools.javac.tree.JCTree.JCSynchronized;
 import com.sun.tools.javac.tree.JCTree.JCThrow;
 import com.sun.tools.javac.tree.JCTree.JCTry;
@@ -84,6 +85,7 @@
 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
 import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
 import com.sun.tools.javac.tree.JCTree.JCWildcard;
+import com.sun.tools.javac.tree.JCTree.JCYield;
 import com.sun.tools.javac.tree.JCTree.LetExpr;
 import com.sun.tools.javac.tree.JCTree.TypeBoundKind;
 import com.sun.tools.javac.tree.TreeInfo;
@@ -259,6 +261,12 @@
     @Override
     public void visitBreak(JCBreak tree) {
         JCBreak that = (JCBreak) parameter;
+        result = tree.label == that.label;
+    }
+
+    @Override
+    public void visitYield(JCYield tree) {
+        JCYield that = (JCYield) parameter;
         result = scan(tree.value, that.value);
     }
 
@@ -499,6 +507,12 @@
     }
 
     @Override
+    public void visitSwitchExpression(JCSwitchExpression tree) {
+        JCSwitchExpression that = (JCSwitchExpression) parameter;
+        result = scan(tree.selector, that.selector) && scan(tree.cases, that.cases);
+    }
+
+    @Override
     public void visitSynchronized(JCSynchronized tree) {
         JCSynchronized that = (JCSynchronized) parameter;
         result = scan(tree.lock, that.lock) && scan(tree.body, that.body);
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/CRTable.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/CRTable.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -377,6 +377,11 @@
             result = sr;
         }
 
+        public void visitYield(JCYield tree) {
+            SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
+            result = sr;
+        }
+
         public void visitContinue(JCContinue tree) {
             SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
             result = sr;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1717,46 +1717,48 @@
 
     public void visitBreak(JCBreak tree) {
         Assert.check(code.isStatementStart());
+        final Env<GenContext> targetEnv = unwindBreak(tree.target);
+        targetEnv.info.addExit(code.branch(goto_));
+        endFinalizerGaps(env, targetEnv);
+    }
+
+    public void visitYield(JCYield tree) {
+        Assert.check(code.isStatementStart());
         final Env<GenContext> targetEnv;
-        if (tree.isValueBreak()) {
-            //restore stack as it was before the switch expression:
-            for (LocalItem li : stackBeforeSwitchExpression) {
-                li.load();
+        //restore stack as it was before the switch expression:
+        for (LocalItem li : stackBeforeSwitchExpression) {
+            li.load();
+        }
+        if (inCondSwitchExpression) {
+            CondItem value = genCond(tree.value, CRT_FLOW_TARGET);
+            Chain falseJumps = value.jumpFalse();
+            targetEnv = unwindBreak(tree.target);
+            code.resolve(value.trueJumps);
+            Chain trueJumps = code.branch(goto_);
+            if (switchExpressionTrueChain == null) {
+                switchExpressionTrueChain = trueJumps;
+            } else {
+                switchExpressionTrueChain =
+                        Code.mergeChains(switchExpressionTrueChain, trueJumps);
             }
-            if (inCondSwitchExpression) {
-                CondItem value = genCond(tree.value, CRT_FLOW_TARGET);
-                Chain falseJumps = value.jumpFalse();
-                targetEnv = unwindBreak(tree);
-                code.resolve(value.trueJumps);
-                Chain trueJumps = code.branch(goto_);
-                if (switchExpressionTrueChain == null) {
-                    switchExpressionTrueChain = trueJumps;
-                } else {
-                    switchExpressionTrueChain =
-                            Code.mergeChains(switchExpressionTrueChain, trueJumps);
-                }
-                if (switchExpressionFalseChain == null) {
-                    switchExpressionFalseChain = falseJumps;
-                } else {
-                    switchExpressionFalseChain =
-                            Code.mergeChains(switchExpressionFalseChain, falseJumps);
-                }
+            if (switchExpressionFalseChain == null) {
+                switchExpressionFalseChain = falseJumps;
             } else {
-                genExpr(tree.value, pt).load();
-                code.state.forceStackTop(tree.target.type);
-                targetEnv = unwindBreak(tree);
-                targetEnv.info.addExit(code.branch(goto_));
+                switchExpressionFalseChain =
+                        Code.mergeChains(switchExpressionFalseChain, falseJumps);
             }
         } else {
-            targetEnv = unwindBreak(tree);
+            genExpr(tree.value, pt).load();
+            code.state.forceStackTop(tree.target.type);
+            targetEnv = unwindBreak(tree.target);
             targetEnv.info.addExit(code.branch(goto_));
         }
         endFinalizerGaps(env, targetEnv);
     }
     //where:
-        private Env<GenContext> unwindBreak(JCBreak tree) {
+        private Env<GenContext> unwindBreak(JCTree target) {
             int tmpPos = code.pendingStatPos;
-            Env<GenContext> targetEnv = unwind(tree.target, env);
+            Env<GenContext> targetEnv = unwind(target, env);
             code.pendingStatPos = tmpPos;
             return targetEnv;
         }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -182,6 +182,8 @@
         this.keepLineMap = keepLineMap;
         this.errorTree = F.Erroneous();
         endPosTable = newEndPosTable(keepEndPositions);
+        this.allowYieldStatement = (!preview.isPreview(Feature.SWITCH_EXPRESSION) || preview.isEnabled()) &&
+                Feature.SWITCH_EXPRESSION.allowedInSource(source);
     }
 
     protected AbstractEndPosTable newEndPosTable(boolean keepEndPositions) {
@@ -211,6 +213,10 @@
      */
     boolean allowThisIdent;
 
+    /** Switch: is yield statement allowed in this source level?
+     */
+    boolean allowYieldStatement;
+
     /** The type of the method receiver, as specified by a first "this" parameter.
      */
     JCVariableDecl receiverParam;
@@ -769,9 +775,10 @@
 
     public JCExpression unannotatedType(boolean allowVar) {
         JCExpression result = term(TYPE);
-
-        if (!allowVar && isRestrictedLocalVarTypeName(result, true)) {
-            syntaxError(result.pos, Errors.VarNotAllowedHere);
+        Name restrictedTypeName;
+
+        if (!allowVar && (restrictedTypeName = restrictedTypeName(result, true)) != null) {
+            syntaxError(result.pos, Errors.RestrictedTypeNotAllowedHere(restrictedTypeName));
         }
 
         return result;
@@ -1377,6 +1384,7 @@
             break;
         case SWITCH:
             checkSourceLevel(Feature.SWITCH_EXPRESSION);
+            allowYieldStatement = true;
             int switchPos = token.pos;
             nextToken();
             JCExpression selector = parExpression();
@@ -1436,7 +1444,7 @@
                     kind = JCCase.RULE;
                 } else {
                     JCExpression value = parseExpression();
-                    stats = List.of(to(F.at(value).Break(value)));
+                    stats = List.of(to(F.at(value).Yield(value)));
                     body = value;
                     kind = JCCase.RULE;
                     accept(SEMI);
@@ -1607,7 +1615,7 @@
         int depth = 0;
         boolean type = false;
         ParensResult defaultResult = ParensResult.PARENS;
-        outer: for (int lookahead = 0 ; ; lookahead++) {
+        outer: for (int lookahead = 0; ; lookahead++) {
             TokenKind tk = S.token(lookahead).kind;
             switch (tk) {
                 case COMMA:
@@ -1782,12 +1790,13 @@
         if (explicitParams) {
             LambdaClassifier lambdaClassifier = new LambdaClassifier();
             for (JCVariableDecl param: params) {
+                Name restrictedTypeName;
                 if (param.vartype != null &&
-                        isRestrictedLocalVarTypeName(param.vartype, false) &&
+                        (restrictedTypeName = restrictedTypeName(param.vartype, false)) != null &&
                         param.vartype.hasTag(TYPEARRAY)) {
                     log.error(DiagnosticFlag.SYNTAX, param.pos,
                         Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS.allowedInSource(source)
-                            ? Errors.VarNotAllowedArray : Errors.VarNotAllowedHere);
+                            ? Errors.RestrictedTypeNotAllowedArray(restrictedTypeName) : Errors.RestrictedTypeNotAllowedHere(restrictedTypeName));
                 }
                 lambdaClassifier.addParameter(param);
                 if (lambdaClassifier.result() == LambdaParameterKind.ERROR) {
@@ -1799,7 +1808,7 @@
             }
             for (JCVariableDecl param: params) {
                 if (param.vartype != null
-                        && isRestrictedLocalVarTypeName(param.vartype, true)) {
+                        && restrictedTypeName(param.vartype, true) != null) {
                     checkSourceLevel(param.pos, Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS);
                     param.startPos = TreeInfo.getStartPos(param.vartype);
                     param.vartype = null;
@@ -1837,7 +1846,7 @@
 
         void addParameter(JCVariableDecl param) {
             if (param.vartype != null && param.name != names.empty) {
-                if (isRestrictedLocalVarTypeName(param.vartype, false)) {
+                if (restrictedTypeName(param.vartype, false) != null) {
                     reduce(LambdaParameterKind.VAR);
                 } else {
                     reduce(LambdaParameterKind.EXPLICIT);
@@ -1944,10 +1953,27 @@
         return args.toList();
     }
 
-    JCMethodInvocation arguments(List<JCExpression> typeArgs, JCExpression t) {
+    JCExpression arguments(List<JCExpression> typeArgs, JCExpression t) {
         int pos = token.pos;
         List<JCExpression> args = arguments();
-        return toP(F.at(pos).Apply(typeArgs, t, args));
+        JCExpression mi = F.at(pos).Apply(typeArgs, t, args);
+        if (t.hasTag(IDENT) && isInvalidUnqualifiedMethodIdentifier(((JCIdent) t).pos,
+                                                                    ((JCIdent) t).name)) {
+            log.error(DiagnosticFlag.SYNTAX, t, Errors.InvalidYield);
+            mi = F.Erroneous(List.of(mi));
+        }
+        return toP(mi);
+    }
+
+    boolean isInvalidUnqualifiedMethodIdentifier(int pos, Name name) {
+        if (name == names.yield) {
+            if (allowYieldStatement) {
+                return true;
+            } else {
+                log.warning(pos, Warnings.InvalidYield);
+            }
+        }
+        return false;
     }
 
     /**  TypeArgumentsOpt = [ TypeArguments ]
@@ -2506,6 +2532,7 @@
 
     /**This method parses a statement appearing inside a block.
      */
+    @SuppressWarnings("fallthrough")
     List<JCStatement> blockStatement() {
         //todo: skip to anchor on error(?)
         int pos = token.pos;
@@ -2543,6 +2570,52 @@
             log.error(DiagnosticFlag.SYNTAX, token.pos, Errors.LocalEnum);
             dc = token.comment(CommentStyle.JAVADOC);
             return List.of(classOrInterfaceOrEnumDeclaration(modifiersOpt(), dc));
+        case IDENTIFIER:
+            if (token.name() == names.yield && allowYieldStatement) {
+                Token next = S.token(1);
+                boolean isYieldStatement;
+                switch (next.kind) {
+                    case PLUS: case SUB: case STRINGLITERAL: case CHARLITERAL:
+                    case INTLITERAL: case FLOATLITERAL: case DOUBLELITERAL:
+                    case NULL: case IDENTIFIER: case TRUE: case FALSE:
+                    case NEW: case SWITCH: case THIS: case SUPER:
+                        isYieldStatement = true;
+                        break;
+                    case PLUSPLUS: case SUBSUB:
+                        isYieldStatement = S.token(2).kind != SEMI;
+                        break;
+                    case LPAREN:
+                        int lookahead = 2;
+                        int balance = 1;
+                        boolean hasComma = false;
+                        Token l;
+                        while ((l = S.token(lookahead)).kind != EOF && balance != 0) {
+                            switch (l.kind) {
+                                case LPAREN: balance++; break;
+                                case RPAREN: balance--; break;
+                                case COMMA: if (balance == 1) hasComma = true; break;
+                            }
+                            lookahead++;
+                        }
+                        isYieldStatement = (!hasComma && lookahead != 3) || l.kind == ARROW;
+                        break;
+                    case SEMI: //error recovery - this is not a valid statement:
+                        isYieldStatement = true;
+                        break;
+                    default:
+                        isYieldStatement = false;
+                        break;
+                }
+
+                if (isYieldStatement) {
+                    nextToken();
+                    JCExpression t = term(EXPR);
+                    accept(SEMI);
+                    return List.of(toP(F.at(pos).Yield(t)));
+                }
+
+                //else intentional fall-through
+            }
         default:
             Token prevToken = token;
             JCExpression t = term(EXPR | TYPE);
@@ -2702,9 +2775,9 @@
         }
         case BREAK: {
             nextToken();
-            JCExpression value = token.kind == SEMI ? null : parseExpression();
+            Name label = LAX_IDENTIFIER.accepts(token.kind) ? ident() : null;
             accept(SEMI);
-            JCBreak t = toP(F.at(pos).Break(value));
+            JCBreak t = toP(F.at(pos).Break(label));
             return t;
         }
         case CONTINUE: {
@@ -3181,14 +3254,14 @@
         int startPos = Position.NOPOS;
         if (elemType.hasTag(IDENT)) {
             Name typeName = ((JCIdent)elemType).name;
-            if (isRestrictedLocalVarTypeName(typeName, pos, !compound && localDecl)) {
+            if (isRestrictedTypeName(typeName, pos, !compound && localDecl)) {
                 if (type.hasTag(TYPEARRAY) && !compound) {
                     //error - 'var' and arrays
-                    reportSyntaxError(pos, Errors.VarNotAllowedArray);
+                    reportSyntaxError(pos, Errors.RestrictedTypeNotAllowedArray(typeName));
                 } else {
                     if(compound)
                         //error - 'var' in compound local var decl
-                        reportSyntaxError(pos, Errors.VarNotAllowedCompound);
+                        reportSyntaxError(pos, Errors.RestrictedTypeNotAllowedCompound(typeName));
                     startPos = TreeInfo.getStartPos(mods);
                     if (startPos == Position.NOPOS)
                         startPos = TreeInfo.getStartPos(type);
@@ -3204,23 +3277,30 @@
         return result;
     }
 
-    boolean isRestrictedLocalVarTypeName(JCExpression e, boolean shouldWarn) {
+    Name restrictedTypeName(JCExpression e, boolean shouldWarn) {
         switch (e.getTag()) {
             case IDENT:
-                return isRestrictedLocalVarTypeName(((JCIdent)e).name, e.pos, shouldWarn);
+                return isRestrictedTypeName(((JCIdent)e).name, e.pos, shouldWarn) ? ((JCIdent)e).name : null;
             case TYPEARRAY:
-                return isRestrictedLocalVarTypeName(((JCArrayTypeTree)e).elemtype, shouldWarn);
+                return restrictedTypeName(((JCArrayTypeTree)e).elemtype, shouldWarn);
             default:
-                return false;
+                return null;
         }
     }
 
-    boolean isRestrictedLocalVarTypeName(Name name, int pos, boolean shouldWarn) {
+    boolean isRestrictedTypeName(Name name, int pos, boolean shouldWarn) {
         if (name == names.var) {
             if (Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source)) {
                 return true;
             } else if (shouldWarn) {
-                log.warning(pos, Warnings.VarNotAllowed);
+                log.warning(pos, Warnings.RestrictedTypeNotAllowed(name, Source.JDK10));
+            }
+        }
+        if (name == names.yield) {
+            if (allowYieldStatement) {
+                return true;
+            } else if (shouldWarn) {
+                log.warning(pos, Warnings.RestrictedTypeNotAllowedPreview(name, Source.JDK13));
             }
         }
         return false;
@@ -3614,8 +3694,8 @@
     Name typeName() {
         int pos = token.pos;
         Name name = ident();
-        if (isRestrictedLocalVarTypeName(name, pos, true)) {
-            reportSyntaxError(pos, Errors.VarNotAllowed);
+        if (isRestrictedTypeName(name, pos, true)) {
+            reportSyntaxError(pos, Errors.RestrictedTypeNotAllowed(name, name == names.var ? Source.JDK10 : Source.JDK13));
         }
         return name;
     }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Wed Jun 12 10:02:49 2019 +0530
@@ -188,17 +188,14 @@
 compiler.err.break.outside.switch.loop=\
     break outside switch or loop
 
-compiler.err.break.missing.value=\
-    missing break value
-
 compiler.err.break.outside.switch.expression=\
-    break outside of enclosing switch expression
+    attempt to break out of a switch expression
 
 compiler.err.continue.outside.switch.expression=\
-    continue outside of enclosing switch expression
+    attempt to continue out of a switch expression
 
 compiler.err.return.outside.switch.expression=\
-    return outside of enclosing switch expression
+    attempt to return out of a switch expression
 
 compiler.err.rule.completes.normally=\
     switch rule completes without providing a value\n\
@@ -208,17 +205,20 @@
     switch expression completes without providing a value\n\
     (switch expressions must either provide a value or throw for all possible input values)
 
-# 0: name
-compiler.err.break.ambiguous.target=\
-    ambiguous reference to ''{0}''\n\
-    (''{0}'' is both a label and an expression)
-
-# 0: tree tag
-compiler.err.break.expr.not.immediate=\
-    value break not supported in ''{0}''
-
-compiler.err.break.complex.value.no.switch.expression=\
-    unexpected value break
+compiler.err.no.switch.expression =\
+    yield outside of switch expression
+
+compiler.err.no.switch.expression.qualify=\
+    yield outside of switch expression\n\
+    (to invoke a method called yield, qualify the yield with a receiver or type name)
+
+compiler.err.invalid.yield=\
+    invalid use of a restricted identifier ''yield''\n\
+    (to invoke a method called yield, qualify the yield with a receiver or type name)
+
+compiler.warn.invalid.yield=\
+    ''yield'' may become a restricted identifier in a future release\n\
+    (to invoke a method called yield, qualify the yield with a receiver or type name)
 
 compiler.err.switch.expression.empty=\
     switch expression does not have any case clauses
@@ -1267,29 +1267,43 @@
 compiler.err.undef.label=\
     undefined label: {0}
 
-compiler.err.illegal.ref.to.var.type=\
-    illegal reference to restricted type ''var''
-
-compiler.err.var.not.allowed=\
-    ''var'' not allowed here\n\
-    as of release 10, ''var'' is a restricted local variable type and cannot be used for type declarations
-
-compiler.warn.var.not.allowed=\
-    as of release 10, ''var'' is a restricted local variable type and cannot be used for type declarations or as the element type of an array
+# 0: name
+compiler.err.illegal.ref.to.restricted.type=\
+    illegal reference to restricted type ''{0}''
+
+# 0: name
+compiler.warn.illegal.ref.to.restricted.type=\
+    illegal reference to restricted type ''{0}''
+
+# 0: name, 1: source
+compiler.err.restricted.type.not.allowed=\
+    ''{0}'' not allowed here\n\
+    as of release {1}, ''{0}'' is a restricted type name and cannot be used for type declarations
+
+# 0: name, 1: source
+compiler.warn.restricted.type.not.allowed=\
+    as of release {1}, ''{0}'' is a restricted type name and cannot be used for type declarations or as the element type of an array
+
+# 0: name, 1: source
+compiler.warn.restricted.type.not.allowed.preview=\
+    ''{0}'' may become a restricted type name in a future release and may be unusable for type declarations or as the element type of an array
 
 # 0: name (variable), 1: message segment
 compiler.err.cant.infer.local.var.type=\
     cannot infer type for local variable {0}\n\
     ({1})
 
-compiler.err.var.not.allowed.here=\
-    ''var'' is not allowed here
-
-compiler.err.var.not.allowed.array=\
-    ''var'' is not allowed as an element type of an array
-
-compiler.err.var.not.allowed.compound=\
-    ''var'' is not allowed in a compound declaration
+# 0: name
+compiler.err.restricted.type.not.allowed.here=\
+    ''{0}'' is not allowed here
+
+# 0: name
+compiler.err.restricted.type.not.allowed.array=\
+    ''{0}'' is not allowed as an element type of an array
+
+# 0: name
+compiler.err.restricted.type.not.allowed.compound=\
+    ''{0}'' is not allowed in a compound declaration
 
 # 0: fragment
 compiler.err.invalid.lambda.parameter.declaration=\
@@ -2666,22 +2680,6 @@
 compiler.misc.kindname.instance.init=\
     instance initializer
 
-# the following are names of tree kinds:
-compiler.misc.tree.tag.forloop=\
-    for
-
-compiler.misc.tree.tag.foreachloop=\
-    for
-
-compiler.misc.tree.tag.whileloop=\
-    while
-
-compiler.misc.tree.tag.doloop=\
-    do
-
-compiler.misc.tree.tag.switch=\
-    switch
-
 #####
 
 compiler.misc.no.args=\
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -187,6 +187,10 @@
          */
         BREAK,
 
+        /** Yield statements, of type Yield.
+         */
+        YIELD,
+
         /** Continue statements, of type Continue.
          */
         CONTINUE,
@@ -1551,10 +1555,10 @@
      * A break from a loop or switch.
      */
     public static class JCBreak extends JCStatement implements BreakTree {
-        public JCExpression value;
+        public Name label;
         public JCTree target;
-        protected JCBreak(JCExpression value, JCTree target) {
-            this.value = value;
+        protected JCBreak(Name label, JCTree target) {
+            this.label = label;
             this.target = target;
         }
         @Override
@@ -1567,11 +1571,8 @@
         public Kind getKind() { return Kind.BREAK; }
         @DefinedBy(Api.COMPILER_TREE)
         public Name getLabel() {
-            return value != null && value.getKind() == Kind.IDENTIFIER ? ((JCIdent) value).getName() : null;
+            return label;
         }
-        @DefinedBy(Api.COMPILER_TREE)
-        @SuppressWarnings("removal")
-        public JCExpression getValue() { return value; }
         @Override @DefinedBy(Api.COMPILER_TREE)
         public <R,D> R accept(TreeVisitor<R,D> v, D d) {
             return v.visitBreak(this, d);
@@ -1583,6 +1584,33 @@
     }
 
     /**
+     * A break-with from a switch expression.
+     */
+    @SuppressWarnings("removal")
+    public static class JCYield extends JCStatement implements YieldTree {
+        public JCExpression value;
+        public JCTree target;
+        protected JCYield(JCExpression value, JCTree target) {
+            this.value = value;
+            this.target = target;
+        }
+        @Override
+        public void accept(Visitor v) { v.visitYield(this); }
+        @DefinedBy(Api.COMPILER_TREE)
+        public Kind getKind() { return Kind.YIELD; }
+        @DefinedBy(Api.COMPILER_TREE)
+        public JCExpression getValue() { return value; }
+        @Override @DefinedBy(Api.COMPILER_TREE)
+        public <R,D> R accept(TreeVisitor<R,D> v, D d) {
+            return v.visitYield(this, d);
+        }
+        @Override
+        public Tag getTag() {
+            return YIELD;
+        }
+    }
+
+    /**
      * A continue of a loop.
      */
     public static class JCContinue extends JCStatement implements ContinueTree {
@@ -3091,7 +3119,8 @@
                                 JCExpression elsepart);
         JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart);
         JCExpressionStatement Exec(JCExpression expr);
-        JCBreak Break(JCExpression value);
+        JCBreak Break(Name label);
+        JCYield Yield(JCExpression value);
         JCContinue Continue(Name label);
         JCReturn Return(JCExpression expr);
         JCThrow Throw(JCExpression expr);
@@ -3162,6 +3191,7 @@
         public void visitIf(JCIf that)                       { visitTree(that); }
         public void visitExec(JCExpressionStatement that)    { visitTree(that); }
         public void visitBreak(JCBreak that)                 { visitTree(that); }
+        public void visitYield(JCYield that)                 { visitTree(that); }
         public void visitContinue(JCContinue that)           { visitTree(that); }
         public void visitReturn(JCReturn that)               { visitTree(that); }
         public void visitThrow(JCThrow that)                 { visitTree(that); }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -982,7 +982,18 @@
     public void visitBreak(JCBreak tree) {
         try {
             print("break");
-            if (tree.value != null) print(" " + tree.value);
+            if (tree.label != null) print(" " + tree.label);
+            print(";");
+        } catch (IOException e) {
+            throw new UncheckedIOException(e);
+        }
+    }
+
+    public void visitYield(JCYield tree) {
+        try {
+            print("yield");
+            print(" ");
+            printExpr(tree.value);
             print(";");
         } catch (IOException e) {
             throw new UncheckedIOException(e);
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -140,8 +140,15 @@
     @DefinedBy(Api.COMPILER_TREE)
     public JCTree visitBreak(BreakTree node, P p) {
         JCBreak t = (JCBreak) node;
+        return M.at(t.pos).Break(t.label);
+    }
+
+    @DefinedBy(Api.COMPILER_TREE)
+    @SuppressWarnings("removal")
+    public JCTree visitYield(YieldTree node, P p) {
+        JCYield t = (JCYield) node;
         JCExpression value = copy(t.value, p);
-        return M.at(t.pos).Break(value);
+        return M.at(t.pos).Yield(value);
     }
 
     @DefinedBy(Api.COMPILER_TREE)
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -333,12 +333,18 @@
         return tree;
     }
 
-    public JCBreak Break(JCExpression label) {
+    public JCBreak Break(Name label) {
         JCBreak tree = new JCBreak(label, null);
         tree.pos = pos;
         return tree;
     }
 
+    public JCYield Yield(JCExpression value) {
+        JCYield tree = new JCYield(value, null);
+        tree.pos = pos;
+        return tree;
+    }
+
     public JCContinue Continue(Name label) {
         JCContinue tree = new JCContinue(label, null);
         tree.pos = pos;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -219,6 +219,9 @@
     }
 
     public void visitBreak(JCBreak tree) {
+    }
+
+    public void visitYield(JCYield tree) {
         scan(tree.value);
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -258,8 +258,11 @@
     }
 
     public void visitBreak(JCBreak tree) {
-        if (tree.isValueBreak())
-            tree.value = translate(tree.value);
+        result = tree;
+    }
+
+    public void visitYield(JCYield tree) {
+        tree.value = translate(tree.value);
         result = tree;
     }
 
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -554,6 +554,13 @@
             }
         }
 
+    /**Is an error reported at the given pos (inside the current source)?*/
+    public boolean hasErrorOn(DiagnosticPosition pos) {
+        JavaFileObject file = source != null ? source.fileObject : null;
+
+        return file != null && recorded.contains(new Pair<>(file, pos.getPreferredPosition()));
+    }
+
     /** Prompt user after an error.
      */
     public void prompt() {
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,6 +70,7 @@
     public final Name uses;
     public final Name open;
     public final Name with;
+    public final Name yield;
 
     // field and method names
     public final Name _name;
@@ -219,6 +220,7 @@
         uses = fromString("uses");
         open = fromString("open");
         with = fromString("with");
+        yield = fromString("yield");
 
         // field and method names
         _name = fromString("name");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11AEADCipher.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,750 @@
+/* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.security.pkcs11;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Locale;
+
+import java.security.*;
+import java.security.spec.*;
+
+import javax.crypto.*;
+import javax.crypto.spec.*;
+
+import sun.nio.ch.DirectBuffer;
+import sun.security.jca.JCAUtil;
+import sun.security.pkcs11.wrapper.*;
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
+
+/**
+ * P11 AEAD Cipher implementation class. This class currently supports
+ * AES with GCM mode.
+ *
+ * Note that AEAD modes do not use padding, so this class does not have
+ * its own padding impl. In addition, NSS CKM_AES_GCM only supports single-part
+ * encryption/decryption, thus the current impl uses PKCS#11 C_Encrypt/C_Decrypt
+ * calls and buffers data until doFinal is called.
+ *
+ * Note that PKCS#11 standard currently only supports GCM and CCM AEAD modes.
+ * There are no provisions for other AEAD modes yet.
+ *
+ * @since   13
+ */
+final class P11AEADCipher extends CipherSpi {
+
+    // mode constant for GCM mode
+    private static final int MODE_GCM = 10;
+
+    // default constants for GCM
+    private static final int GCM_DEFAULT_TAG_LEN = 16;
+    private static final int GCM_DEFAULT_IV_LEN = 16;
+
+    private static final String ALGO = "AES";
+
+    // token instance
+    private final Token token;
+
+    // mechanism id
+    private final long mechanism;
+
+    // mode, one of MODE_* above
+    private final int blockMode;
+
+    // acceptable key size, -1 if more than 1 key sizes are accepted
+    private final int fixedKeySize;
+
+    // associated session, if any
+    private Session session = null;
+
+    // key, if init() was called
+    private P11Key p11Key = null;
+
+    // flag indicating whether an operation is initialized
+    private boolean initialized = false;
+
+    // falg indicating encrypt or decrypt mode
+    private boolean encrypt = true;
+
+    // parameters
+    private byte[] iv = null;
+    private int tagLen = -1;
+    private SecureRandom random = JCAUtil.getSecureRandom();
+
+    // dataBuffer is cleared upon doFinal calls
+    private ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
+    // aadBuffer is cleared upon successful init calls
+    private ByteArrayOutputStream aadBuffer = new ByteArrayOutputStream();
+    private boolean updateCalled = false;
+
+    private boolean requireReinit = false;
+    private P11Key lastEncKey = null;
+    private byte[] lastEncIv = null;
+
+    P11AEADCipher(Token token, String algorithm, long mechanism)
+            throws PKCS11Exception, NoSuchAlgorithmException {
+        super();
+        this.token = token;
+        this.mechanism = mechanism;
+
+        String[] algoParts = algorithm.split("/");
+        if (algoParts.length != 3) {
+            throw new ProviderException("Unsupported Transformation format: " +
+                    algorithm);
+        }
+        if (!algoParts[0].startsWith("AES")) {
+            throw new ProviderException("Only support AES for AEAD cipher mode");
+        }
+        int index = algoParts[0].indexOf('_');
+        if (index != -1) {
+            // should be well-formed since we specify what we support
+            fixedKeySize = Integer.parseInt(algoParts[0].substring(index+1)) >> 3;
+        } else {
+            fixedKeySize = -1;
+        }
+        this.blockMode = parseMode(algoParts[1]);
+        if (!algoParts[2].equals("NoPadding")) {
+            throw new ProviderException("Only NoPadding is supported for AEAD cipher mode");
+        }
+    }
+
+    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
+        // Disallow change of mode for now since currently it's explicitly
+        // defined in transformation strings
+        throw new NoSuchAlgorithmException("Unsupported mode " + mode);
+    }
+
+    private int parseMode(String mode) throws NoSuchAlgorithmException {
+        mode = mode.toUpperCase(Locale.ENGLISH);
+        int result;
+        if (mode.equals("GCM")) {
+            result = MODE_GCM;
+        } else {
+            throw new NoSuchAlgorithmException("Unsupported mode " + mode);
+        }
+        return result;
+    }
+
+    // see JCE spec
+    protected void engineSetPadding(String padding)
+            throws NoSuchPaddingException {
+        // Disallow change of padding for now since currently it's explicitly
+        // defined in transformation strings
+        throw new NoSuchPaddingException("Unsupported padding " + padding);
+    }
+
+    // see JCE spec
+    protected int engineGetBlockSize() {
+        return 16; // constant; only AES is supported
+    }
+
+    // see JCE spec
+    protected int engineGetOutputSize(int inputLen) {
+        return doFinalLength(inputLen);
+    }
+
+    // see JCE spec
+    protected byte[] engineGetIV() {
+        return (iv == null) ? null : iv.clone();
+    }
+
+    // see JCE spec
+    protected AlgorithmParameters engineGetParameters() {
+        if (encrypt && iv == null && tagLen == -1) {
+            switch (blockMode) {
+                case MODE_GCM:
+                    iv = new byte[GCM_DEFAULT_IV_LEN];
+                    tagLen = GCM_DEFAULT_TAG_LEN;
+                    break;
+                default:
+                    throw new ProviderException("Unsupported mode");
+            }
+            random.nextBytes(iv);
+        }
+        try {
+            AlgorithmParameterSpec spec;
+            String apAlgo;
+            switch (blockMode) {
+                case MODE_GCM:
+                    apAlgo = "GCM";
+                    spec = new GCMParameterSpec(tagLen << 3, iv);
+                    break;
+                default:
+                    throw new ProviderException("Unsupported mode");
+            }
+            AlgorithmParameters params =
+                AlgorithmParameters.getInstance(apAlgo);
+            params.init(spec);
+            return params;
+        } catch (GeneralSecurityException e) {
+            // NoSuchAlgorithmException, NoSuchProviderException
+            // InvalidParameterSpecException
+            throw new ProviderException("Could not encode parameters", e);
+        }
+    }
+
+    // see JCE spec
+    protected void engineInit(int opmode, Key key, SecureRandom sr)
+            throws InvalidKeyException {
+        if (opmode == Cipher.DECRYPT_MODE) {
+            throw new InvalidKeyException("Parameters required for decryption");
+        }
+        updateCalled = false;
+        try {
+            implInit(opmode, key, null, -1, sr);
+        } catch (InvalidAlgorithmParameterException e) {
+            throw new InvalidKeyException("init() failed", e);
+        }
+    }
+
+    // see JCE spec
+    protected void engineInit(int opmode, Key key,
+            AlgorithmParameterSpec params, SecureRandom sr)
+            throws InvalidKeyException, InvalidAlgorithmParameterException {
+        if (opmode == Cipher.DECRYPT_MODE && params == null) {
+            throw new InvalidAlgorithmParameterException
+                    ("Parameters required for decryption");
+        }
+        updateCalled = false;
+        byte[] ivValue = null;
+        int tagLen = -1;
+        if (params != null) {
+            switch (blockMode) {
+            case MODE_GCM:
+                if (!(params instanceof GCMParameterSpec)) {
+                    throw new InvalidAlgorithmParameterException
+                        ("Only GCMParameterSpec is supported");
+                }
+                ivValue = ((GCMParameterSpec) params).getIV();
+                tagLen = ((GCMParameterSpec) params).getTLen() >> 3;
+            break;
+            default:
+                throw new ProviderException("Unsupported mode");
+            }
+        }
+        implInit(opmode, key, ivValue, tagLen, sr);
+    }
+
+    // see JCE spec
+    protected void engineInit(int opmode, Key key, AlgorithmParameters params,
+            SecureRandom sr)
+            throws InvalidKeyException, InvalidAlgorithmParameterException {
+        if (opmode == Cipher.DECRYPT_MODE && params == null) {
+            throw new InvalidAlgorithmParameterException
+                    ("Parameters required for decryption");
+        }
+        updateCalled = false;
+        try {
+            AlgorithmParameterSpec paramSpec = null;
+            if (params != null) {
+                switch (blockMode) {
+                    case MODE_GCM:
+                        paramSpec =
+                            params.getParameterSpec(GCMParameterSpec.class);
+                        break;
+                    default:
+                        throw new ProviderException("Unsupported mode");
+                }
+            }
+            engineInit(opmode, key, paramSpec, sr);
+        } catch (InvalidParameterSpecException ex) {
+            throw new InvalidAlgorithmParameterException(ex);
+        }
+    }
+
+    // actual init() implementation
+    private void implInit(int opmode, Key key, byte[] iv, int tagLen,
+        SecureRandom sr)
+        throws InvalidKeyException, InvalidAlgorithmParameterException {
+        reset(true);
+        if (fixedKeySize != -1 && key.getEncoded().length != fixedKeySize) {
+            throw new InvalidKeyException("Key size is invalid");
+        }
+        P11Key newKey = P11SecretKeyFactory.convertKey(token, key, ALGO);
+        switch (opmode) {
+            case Cipher.ENCRYPT_MODE:
+                encrypt = true;
+                requireReinit = Arrays.equals(iv, lastEncIv) &&
+                        (newKey == lastEncKey);
+                if (requireReinit) {
+                    throw new InvalidAlgorithmParameterException
+                        ("Cannot reuse iv for GCM encryption");
+                }
+                break;
+            case Cipher.DECRYPT_MODE:
+                encrypt = false;
+                requireReinit = false;
+                break;
+            default:
+                throw new InvalidAlgorithmParameterException
+                        ("Unsupported mode: " + opmode);
+        }
+
+        // decryption without parameters is checked in all engineInit() calls
+        if (sr != null) {
+            this.random = sr;
+        }
+        if (iv == null && tagLen == -1) {
+            // generate default values
+            switch (blockMode) {
+                case MODE_GCM:
+                    iv = new byte[GCM_DEFAULT_IV_LEN];
+                    this.random.nextBytes(iv);
+                    tagLen = GCM_DEFAULT_TAG_LEN;
+                    break;
+                default:
+                    throw new ProviderException("Unsupported mode");
+            }
+        }
+        this.iv = iv;
+        this.tagLen = tagLen;
+        this.p11Key = newKey;
+        try {
+            initialize();
+        } catch (PKCS11Exception e) {
+            throw new InvalidKeyException("Could not initialize cipher", e);
+        }
+    }
+
+    private void cancelOperation() {
+        try {
+            if (session.hasObjects() == false) {
+                session = token.killSession(session);
+                return;
+            } else {
+                // cancel operation by finishing it
+                int bufLen = doFinalLength(0);
+                byte[] buffer = new byte[bufLen];
+
+                if (encrypt) {
+                    token.p11.C_Encrypt(session.id(), 0, buffer, 0, bufLen,
+                            0, buffer, 0, bufLen);
+                } else {
+                    token.p11.C_Decrypt(session.id(), 0, buffer, 0, bufLen,
+                            0, buffer, 0, bufLen);
+                }
+            }
+        } catch (PKCS11Exception e) {
+            throw new ProviderException("Cancel failed", e);
+        }
+    }
+
+    private void ensureInitialized() throws PKCS11Exception {
+        if (initialized && aadBuffer.size() > 0) {
+            // need to cancel first to avoid CKR_OPERATION_ACTIVE
+            reset(true);
+        }
+        if (!initialized) {
+            initialize();
+        }
+    }
+
+    private void initialize() throws PKCS11Exception {
+        if (p11Key == null) {
+            throw new ProviderException(
+                    "Operation cannot be performed without"
+                    + " calling engineInit first");
+        }
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
+
+        token.ensureValid();
+
+        byte[] aad = (aadBuffer.size() > 0? aadBuffer.toByteArray() : null);
+
+        long p11KeyID = p11Key.getKeyID();
+        try {
+            if (session == null) {
+                session = token.getOpSession();
+            }
+            CK_MECHANISM mechWithParams;
+            switch (blockMode) {
+                case MODE_GCM:
+                    mechWithParams = new CK_MECHANISM(mechanism,
+                        new CK_GCM_PARAMS(tagLen << 3, iv, aad));
+                    break;
+                default:
+                    throw new ProviderException("Unsupported mode: " + blockMode);
+            }
+            if (encrypt) {
+                token.p11.C_EncryptInit(session.id(), mechWithParams,
+                    p11KeyID);
+            } else {
+                token.p11.C_DecryptInit(session.id(), mechWithParams,
+                    p11KeyID);
+            }
+        } catch (PKCS11Exception e) {
+            //e.printStackTrace();
+            p11Key.releaseKeyID();
+            session = token.releaseSession(session);
+            throw e;
+        } finally {
+            dataBuffer.reset();
+            aadBuffer.reset();
+        }
+        initialized = true;
+    }
+
+    // if doFinal(inLen) is called, how big does the output buffer have to be?
+    private int doFinalLength(int inLen) {
+        if (inLen < 0) {
+            throw new ProviderException("Invalid negative input length");
+        }
+
+        int result = inLen + dataBuffer.size();
+        if (encrypt) {
+            result += tagLen;
+        } else {
+            // PKCS11Exception: CKR_BUFFER_TOO_SMALL
+            //result -= tagLen;
+        }
+        return result;
+    }
+
+    // reset the states to the pre-initialized values
+    private void reset(boolean doCancel) {
+        if (!initialized) {
+            return;
+        }
+        try {
+            if (session == null) {
+                return;
+            }
+            if (doCancel && token.explicitCancel) {
+                cancelOperation();
+            }
+        } finally {
+            p11Key.releaseKeyID();
+            session = token.releaseSession(session);
+        }
+        initialized = false;
+    }
+
+    // see JCE spec
+    protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
+        updateCalled = true;
+        int n = implUpdate(in, inOfs, inLen);
+        return new byte[0];
+    }
+
+    // see JCE spec
+    protected int engineUpdate(byte[] in, int inOfs, int inLen, byte[] out,
+            int outOfs) throws ShortBufferException {
+        updateCalled = true;
+        implUpdate(in, inOfs, inLen);
+        return 0;
+    }
+
+    // see JCE spec
+    @Override
+    protected int engineUpdate(ByteBuffer inBuffer, ByteBuffer outBuffer)
+            throws ShortBufferException {
+        updateCalled = true;
+        implUpdate(inBuffer);
+        return 0;
+    }
+
+    // see JCE spec
+    @Override
+    protected synchronized void engineUpdateAAD(byte[] src, int srcOfs, int srcLen)
+            throws IllegalStateException {
+        if ((src == null) || (srcOfs < 0) || (srcOfs + srcLen > src.length)) {
+            throw new IllegalArgumentException("Invalid AAD");
+        }
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
+        if (p11Key == null) {
+            throw new IllegalStateException("Need to initialize Cipher first");
+        }
+        if (updateCalled) {
+            throw new IllegalStateException
+                ("Update has been called; no more AAD data");
+        }
+        aadBuffer.write(src, srcOfs, srcLen);
+    }
+
+    // see JCE spec
+    @Override
+    protected void engineUpdateAAD(ByteBuffer src)
+            throws IllegalStateException {
+        if (src == null) {
+            throw new IllegalArgumentException("Invalid AAD");
+        }
+        byte[] srcBytes = new byte[src.remaining()];
+        src.get(srcBytes);
+        engineUpdateAAD(srcBytes, 0, srcBytes.length);
+    }
+
+    // see JCE spec
+    protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
+            throws IllegalBlockSizeException, BadPaddingException {
+        int minOutLen = doFinalLength(inLen);
+        try {
+            byte[] out = new byte[minOutLen];
+            int n = engineDoFinal(in, inOfs, inLen, out, 0);
+            return P11Util.convert(out, 0, n);
+        } catch (ShortBufferException e) {
+            // convert since the output length is calculated by doFinalLength()
+            throw new ProviderException(e);
+        } finally {
+            updateCalled = false;
+        }
+    }
+    // see JCE spec
+    protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
+            int outOfs) throws ShortBufferException, IllegalBlockSizeException,
+            BadPaddingException {
+        try {
+            return implDoFinal(in, inOfs, inLen, out, outOfs, out.length - outOfs);
+        } finally {
+            updateCalled = false;
+        }
+    }
+
+    // see JCE spec
+    @Override
+    protected int engineDoFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
+            throws ShortBufferException, IllegalBlockSizeException,
+            BadPaddingException {
+        try {
+            return implDoFinal(inBuffer, outBuffer);
+        } finally {
+            updateCalled = false;
+        }
+    }
+
+    private int implUpdate(byte[] in, int inOfs, int inLen) {
+        if (inLen > 0) {
+            updateCalled = true;
+            try {
+                ensureInitialized();
+            } catch (PKCS11Exception e) {
+                //e.printStackTrace();
+                reset(false);
+                throw new ProviderException("update() failed", e);
+            }
+            dataBuffer.write(in, inOfs, inLen);
+        }
+        // always 0 as NSS only supports single-part encryption/decryption
+        return 0;
+    }
+
+    private int implUpdate(ByteBuffer inBuf) {
+        int inLen = inBuf.remaining();
+        if (inLen > 0) {
+            try {
+                ensureInitialized();
+            } catch (PKCS11Exception e) {
+                reset(false);
+                throw new ProviderException("update() failed", e);
+            }
+            byte[] data = new byte[inLen];
+            inBuf.get(data);
+            dataBuffer.write(data, 0, data.length);
+        }
+        // always 0 as NSS only supports single-part encryption/decryption
+        return 0;
+    }
+
+    private int implDoFinal(byte[] in, int inOfs, int inLen,
+            byte[] out, int outOfs, int outLen)
+            throws ShortBufferException, IllegalBlockSizeException,
+            BadPaddingException {
+        int requiredOutLen = doFinalLength(inLen);
+        if (outLen < requiredOutLen) {
+            throw new ShortBufferException();
+        }
+        boolean doCancel = true;
+        try {
+            ensureInitialized();
+            if (dataBuffer.size() > 0) {
+                if (in != null && inOfs > 0 && inLen > 0 &&
+                    inOfs < (in.length - inLen)) {
+                    dataBuffer.write(in, inOfs, inLen);
+                }
+                in = dataBuffer.toByteArray();
+                inOfs = 0;
+                inLen = in.length;
+            }
+            int k = 0;
+            if (encrypt) {
+                k = token.p11.C_Encrypt(session.id(), 0, in, inOfs, inLen,
+                        0, out, outOfs, outLen);
+                doCancel = false;
+            } else {
+                // Special handling to match SunJCE provider behavior
+                if (inLen == 0) {
+                    return 0;
+                }
+                k = token.p11.C_Decrypt(session.id(), 0, in, inOfs, inLen,
+                        0, out, outOfs, outLen);
+                doCancel = false;
+            }
+            return k;
+        } catch (PKCS11Exception e) {
+            doCancel = false;
+            handleException(e);
+            throw new ProviderException("doFinal() failed", e);
+        } finally {
+            if (encrypt) {
+                lastEncKey = this.p11Key;
+                lastEncIv = this.iv;
+                requireReinit = true;
+            }
+            reset(doCancel);
+        }
+    }
+
+    private int implDoFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
+            throws ShortBufferException, IllegalBlockSizeException,
+            BadPaddingException {
+        int outLen = outBuffer.remaining();
+        int inLen = inBuffer.remaining();
+
+        int requiredOutLen = doFinalLength(inLen);
+        if (outLen < requiredOutLen) {
+            throw new ShortBufferException();
+        }
+
+        boolean doCancel = true;
+        try {
+            ensureInitialized();
+
+            long inAddr = 0;
+            byte[] in = null;
+            int inOfs = 0;
+            if (dataBuffer.size() > 0) {
+                if (inLen > 0) {
+                    byte[] temp = new byte[inLen];
+                    inBuffer.get(temp);
+                    dataBuffer.write(temp, 0, temp.length);
+                }
+                in = dataBuffer.toByteArray();
+                inOfs = 0;
+                inLen = in.length;
+            } else {
+                if (inBuffer instanceof DirectBuffer) {
+                    inAddr = ((DirectBuffer) inBuffer).address();
+                    inOfs = inBuffer.position();
+                } else {
+                    if (inBuffer.hasArray()) {
+                        in = inBuffer.array();
+                        inOfs = inBuffer.position() + inBuffer.arrayOffset();
+                    } else {
+                        in = new byte[inLen];
+                        inBuffer.get(in);
+                    }
+                }
+            }
+            long outAddr = 0;
+            byte[] outArray = null;
+            int outOfs = 0;
+            if (outBuffer instanceof DirectBuffer) {
+                outAddr = ((DirectBuffer) outBuffer).address();
+                outOfs = outBuffer.position();
+            } else {
+                if (outBuffer.hasArray()) {
+                    outArray = outBuffer.array();
+                    outOfs = outBuffer.position() + outBuffer.arrayOffset();
+                } else {
+                    outArray = new byte[outLen];
+                }
+            }
+
+            int k = 0;
+            if (encrypt) {
+                k = token.p11.C_Encrypt(session.id(), inAddr, in, inOfs, inLen,
+                        outAddr, outArray, outOfs, outLen);
+                doCancel = false;
+            } else {
+                // Special handling to match SunJCE provider behavior
+                if (inLen == 0) {
+                    return 0;
+                }
+                k = token.p11.C_Decrypt(session.id(), inAddr, in, inOfs, inLen,
+                        outAddr, outArray, outOfs, outLen);
+                doCancel = false;
+            }
+            outBuffer.position(outBuffer.position() + k);
+            return k;
+        } catch (PKCS11Exception e) {
+            doCancel = false;
+            handleException(e);
+            throw new ProviderException("doFinal() failed", e);
+        } finally {
+            if (encrypt) {
+                lastEncKey = this.p11Key;
+                lastEncIv = this.iv;
+                requireReinit = true;
+            }
+            reset(doCancel);
+        }
+    }
+
+    private void handleException(PKCS11Exception e)
+            throws ShortBufferException, IllegalBlockSizeException,
+            BadPaddingException {
+        long errorCode = e.getErrorCode();
+        if (errorCode == CKR_BUFFER_TOO_SMALL) {
+            throw (ShortBufferException)
+                    (new ShortBufferException().initCause(e));
+        } else if (errorCode == CKR_DATA_LEN_RANGE ||
+                   errorCode == CKR_ENCRYPTED_DATA_LEN_RANGE) {
+            throw (IllegalBlockSizeException)
+                    (new IllegalBlockSizeException(e.toString()).initCause(e));
+        } else if (errorCode == CKR_ENCRYPTED_DATA_INVALID) {
+            throw (BadPaddingException)
+                    (new BadPaddingException(e.toString()).initCause(e));
+        }
+    }
+
+    // see JCE spec
+    protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
+            InvalidKeyException {
+        // XXX key wrapping
+        throw new UnsupportedOperationException("engineWrap()");
+    }
+
+    // see JCE spec
+    protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
+            int wrappedKeyType)
+            throws InvalidKeyException, NoSuchAlgorithmException {
+        // XXX key unwrapping
+        throw new UnsupportedOperationException("engineUnwrap()");
+    }
+
+    // see JCE spec
+    @Override
+    protected int engineGetKeySize(Key key) throws InvalidKeyException {
+        int n = P11SecretKeyFactory.convertKey
+                (token, key, ALGO).length();
+        return n;
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11PSSSignature.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,701 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.pkcs11;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import sun.nio.ch.DirectBuffer;
+
+import java.util.Hashtable;
+import java.util.Arrays;
+import java.security.*;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.MGF1ParameterSpec;
+import java.security.spec.PSSParameterSpec;
+import java.security.interfaces.*;
+import sun.security.pkcs11.wrapper.*;
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
+
+
+/**
+ * RSASSA-PSS Signature implementation class. This class currently supports the
+ * following algorithms:
+ *
+ * . RSA-PSS:
+ *   . RSASSA-PSS
+ *   . SHA1withRSASSA-PSS
+ *   . SHA224withRSASSA-PSS
+ *   . SHA256withRSASSA-PSS
+ *   . SHA384withRSASSA-PSS
+ *   . SHA512withRSASSA-PSS
+ *
+ * Note that the underlying PKCS#11 token may support complete signature
+ * algorithm (e.g. CKM_<md>_RSA_PKCS_PSS), or it may just
+ * implement the signature algorithm without hashing (i.e. CKM_RSA_PKCS_PSS).
+ * This class uses what is available and adds whatever extra processing
+ * is needed.
+ *
+ * @since   13
+ */
+final class P11PSSSignature extends SignatureSpi {
+
+    private final static boolean DEBUG = false;
+
+    // mappings of digest algorithms and their output length in bytes
+    private static final Hashtable<String, Integer> DIGEST_LENGTHS =
+        new Hashtable<String, Integer>();
+
+    static {
+        DIGEST_LENGTHS.put("SHA-1", 20);
+        DIGEST_LENGTHS.put("SHA", 20);
+        DIGEST_LENGTHS.put("SHA1", 20);
+        DIGEST_LENGTHS.put("SHA-224", 28);
+        DIGEST_LENGTHS.put("SHA224", 28);
+        DIGEST_LENGTHS.put("SHA-256", 32);
+        DIGEST_LENGTHS.put("SHA256", 32);
+        DIGEST_LENGTHS.put("SHA-384", 48);
+        DIGEST_LENGTHS.put("SHA384", 48);
+        DIGEST_LENGTHS.put("SHA-512", 64);
+        DIGEST_LENGTHS.put("SHA512", 64);
+        DIGEST_LENGTHS.put("SHA-512/224", 28);
+        DIGEST_LENGTHS.put("SHA512/224", 28);
+        DIGEST_LENGTHS.put("SHA-512/256", 32);
+        DIGEST_LENGTHS.put("SHA512/256", 32);
+    }
+
+    // utility method for comparing digest algorithms
+    // NOTE that first argument is assumed to be standard digest name
+    private static boolean isDigestEqual(String stdAlg, String givenAlg) {
+        if (stdAlg == null || givenAlg == null) return false;
+
+        if (givenAlg.indexOf("-") != -1) {
+            return stdAlg.equalsIgnoreCase(givenAlg);
+        } else {
+            if (stdAlg.equals("SHA-1")) {
+                return (givenAlg.equalsIgnoreCase("SHA")
+                        || givenAlg.equalsIgnoreCase("SHA1"));
+            } else {
+                StringBuilder sb = new StringBuilder(givenAlg);
+                // case-insensitive check
+                if (givenAlg.regionMatches(true, 0, "SHA", 0, 3)) {
+                    givenAlg = sb.insert(3, "-").toString();
+                    return stdAlg.equalsIgnoreCase(givenAlg);
+                } else {
+                    throw new ProviderException("Unsupported digest algorithm "
+                            + givenAlg);
+                }
+            }
+        }
+    }
+
+    // token instance
+    private final Token token;
+
+    // algorithm name
+    private final String algorithm;
+
+    // name of the key algorithm, currently just RSA
+    private static final String KEY_ALGO = "RSA";
+
+    // mechanism id
+    private final CK_MECHANISM mechanism;
+
+    // type, one of T_* below
+    private final int type;
+
+    // key instance used, if init*() was called
+    private P11Key p11Key = null;
+
+    // PSS parameters and the flag controlling its access
+    private PSSParameterSpec sigParams = null;
+    private boolean isActive = false;
+
+    // message digest alg, if implied by the algorithm name
+    private final String mdAlg;
+
+    // message digest, if we do the digesting ourselves
+    private MessageDigest md = null;
+
+    // associated session, if any
+    private Session session;
+
+    // mode, one of M_* below
+    private int mode;
+
+    // flag indicating whether an operation is initialized
+    private boolean initialized = false;
+
+    // buffer, for update(byte)
+    private final byte[] buffer = new byte[1];
+
+    // total number of bytes processed in current operation
+    private int bytesProcessed = 0;
+
+    // constant for signing mode
+    private final static int M_SIGN   = 1;
+    // constant for verification mode
+    private final static int M_VERIFY = 2;
+
+    // constant for type digesting, we do the hashing ourselves
+    private final static int T_DIGEST = 1;
+    // constant for type update, token does everything
+    private final static int T_UPDATE = 2;
+
+    P11PSSSignature(Token token, String algorithm, long mechId)
+            throws NoSuchAlgorithmException, PKCS11Exception {
+        super();
+        this.token = token;
+        this.algorithm = algorithm;
+        this.mechanism = new CK_MECHANISM(mechId);
+        int idx = algorithm.indexOf("with");
+        this.mdAlg = (idx == -1? null : algorithm.substring(0, idx));
+        switch ((int)mechId) {
+        case (int)CKM_SHA1_RSA_PKCS_PSS:
+        case (int)CKM_SHA224_RSA_PKCS_PSS:
+        case (int)CKM_SHA256_RSA_PKCS_PSS:
+        case (int)CKM_SHA384_RSA_PKCS_PSS:
+        case (int)CKM_SHA512_RSA_PKCS_PSS:
+            type = T_UPDATE;
+            break;
+        case (int)CKM_RSA_PKCS_PSS:
+            type = T_DIGEST;
+            break;
+        default:
+            throw new ProviderException("Unsupported mechanism: " + mechId);
+        }
+        this.md = null;
+    }
+
+    private void ensureInitialized() throws SignatureException {
+        token.ensureValid();
+        if (this.p11Key == null) {
+            throw new SignatureException("Missing key");
+        }
+        if (this.sigParams == null) {
+            if (this.mdAlg == null) {
+                // PSS Parameters are required for signature verification
+                throw new SignatureException
+                    ("Parameters required for RSASSA-PSS signature");
+            } else {
+                int saltLen = DIGEST_LENGTHS.get(this.mdAlg).intValue();
+                // generate default params for both sign and verify?
+                this.sigParams = new PSSParameterSpec(this.mdAlg,
+                        "MGF1", new MGF1ParameterSpec(this.mdAlg),
+                        saltLen, PSSParameterSpec.TRAILER_FIELD_BC);
+                this.mechanism.setParameter(new CK_RSA_PKCS_PSS_PARAMS(
+                        this.mdAlg, "MGF1", this.mdAlg,
+                        DIGEST_LENGTHS.get(this.mdAlg).intValue()));
+            }
+        }
+
+        if (initialized == false) {
+            initialize();
+        }
+    }
+
+    // reset the states to the pre-initialized values
+    private void reset(boolean doCancel) {
+        if (!initialized) {
+            return;
+        }
+        initialized = false;
+        try {
+            if (session == null) {
+                return;
+            }
+            if (doCancel && token.explicitCancel) {
+                cancelOperation();
+            }
+        } finally {
+            p11Key.releaseKeyID();
+            mechanism.freeHandle();
+            session = token.releaseSession(session);
+            isActive = false;
+        }
+    }
+
+    private void cancelOperation() {
+        token.ensureValid();
+        if (DEBUG) System.out.print("Cancelling operation");
+
+        if (session.hasObjects() == false) {
+            if (DEBUG) System.out.println(" by killing session");
+            session = token.killSession(session);
+            return;
+        }
+        // "cancel" operation by finishing it
+        if (mode == M_SIGN) {
+            try {
+                if (type == T_UPDATE) {
+                    if (DEBUG) System.out.println(" by C_SignFinal");
+                    token.p11.C_SignFinal(session.id(), 0);
+                } else {
+                    byte[] digest =
+                        (md == null? new byte[0] : md.digest());
+                    if (DEBUG) System.out.println(" by C_Sign");
+                    token.p11.C_Sign(session.id(), digest);
+                }
+            } catch (PKCS11Exception e) {
+                throw new ProviderException("cancel failed", e);
+            }
+        } else { // M_VERIFY
+            try {
+                byte[] signature =
+                    new byte[(p11Key.length() + 7) >> 3];
+                if (type == T_UPDATE) {
+                    if (DEBUG) System.out.println(" by C_VerifyFinal");
+                    token.p11.C_VerifyFinal(session.id(), signature);
+                } else {
+                    byte[] digest =
+                        (md == null? new byte[0] : md.digest());
+                    if (DEBUG) System.out.println(" by C_Verify");
+                    token.p11.C_Verify(session.id(), digest, signature);
+                }
+            } catch (PKCS11Exception e) {
+                // will fail since the signature is incorrect
+                // XXX check error code
+            }
+        }
+    }
+
+    // assumes current state is initialized == false
+    private void initialize() {
+        if (DEBUG) System.out.println("Initializing");
+
+        if (p11Key == null) {
+            throw new ProviderException(
+                    "No Key found, call initSign/initVerify first");
+        }
+
+        long keyID = p11Key.getKeyID();
+        try {
+            if (session == null) {
+                session = token.getOpSession();
+            }
+            if (mode == M_SIGN) {
+                token.p11.C_SignInit(session.id(), mechanism, keyID);
+            } else {
+                token.p11.C_VerifyInit(session.id(), mechanism, keyID);
+            }
+        } catch (PKCS11Exception e) {
+            p11Key.releaseKeyID();
+            session = token.releaseSession(session);
+            throw new ProviderException("Initialization failed", e);
+        }
+        if (bytesProcessed != 0) {
+            bytesProcessed = 0;
+            if (md != null) {
+                md.reset();
+            }
+        }
+        initialized = true;
+        isActive = false;
+        if (DEBUG) System.out.println("Initialized");
+    }
+
+    private void checkKeySize(Key key) throws InvalidKeyException {
+        if (DEBUG) System.out.print("Checking Key");
+
+        if (!key.getAlgorithm().equals(KEY_ALGO)) {
+            throw new InvalidKeyException("Only " + KEY_ALGO +
+                " keys are supported");
+        }
+
+        CK_MECHANISM_INFO mechInfo = null;
+        try {
+            mechInfo = token.getMechanismInfo(mechanism.mechanism);
+        } catch (PKCS11Exception e) {
+            // should not happen, ignore for now
+            if (DEBUG) {
+                System.out.println("Unexpected exception");
+                e.printStackTrace();
+            }
+        }
+
+        int keySize = 0; // in bytes
+        if (mechInfo != null) {
+            // check against available native info
+            int minKeySize = (int) mechInfo.ulMinKeySize;
+            int maxKeySize = (int) mechInfo.ulMaxKeySize;
+            if (key instanceof P11Key) {
+                keySize = (((P11Key) key).length() + 7) >> 3;
+            } else if (key instanceof RSAKey) {
+                keySize = ((RSAKey) key).getModulus().bitLength() >> 3;
+            } else {
+                throw new InvalidKeyException("Unrecognized key type " + key);
+            }
+            if ((minKeySize != -1) && (keySize < minKeySize)) {
+                throw new InvalidKeyException(KEY_ALGO +
+                    " key must be at least " + minKeySize + " bytes");
+            }
+            if ((maxKeySize != -1) && (keySize > maxKeySize)) {
+                throw new InvalidKeyException(KEY_ALGO +
+                    " key must be at most " + maxKeySize + " bytes");
+            }
+        }
+        if (this.sigParams != null) {
+            String digestAlg = this.sigParams.getDigestAlgorithm();
+            int sLen = this.sigParams.getSaltLength();
+            int hLen = DIGEST_LENGTHS.get(digestAlg).intValue();
+            int minKeyLen = Math.addExact(Math.addExact(sLen, hLen), 2);
+
+            if (keySize < minKeyLen) {
+                throw new InvalidKeyException
+                    ("Key is too short for current params, need min " + minKeyLen);
+            }
+        }
+    }
+
+    private void setSigParams(AlgorithmParameterSpec p)
+            throws InvalidAlgorithmParameterException {
+        if (p == null) {
+            throw new InvalidAlgorithmParameterException("PSS Parameter required");
+        }
+        if (!(p instanceof PSSParameterSpec)) {
+            throw new InvalidAlgorithmParameterException
+                ("Only PSSParameterSpec is supported");
+        }
+        // no need to validate again if same as current signature parameters
+        PSSParameterSpec params = (PSSParameterSpec) p;
+        if (params == this.sigParams) return;
+
+        String digestAlgorithm = params.getDigestAlgorithm();
+        if (this.mdAlg != null && !isDigestEqual(digestAlgorithm, this.mdAlg)) {
+            throw new InvalidAlgorithmParameterException
+                    ("Digest algorithm in Signature parameters must be " +
+                     this.mdAlg);
+        }
+        Integer digestLen = DIGEST_LENGTHS.get(digestAlgorithm);
+        if (digestLen == null) {
+            throw new InvalidAlgorithmParameterException
+                ("Unsupported digest algorithm in Signature parameters: " +
+                 digestAlgorithm);
+        }
+        if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {
+            throw new InvalidAlgorithmParameterException("Only supports MGF1");
+        }
+        if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
+            throw new InvalidAlgorithmParameterException
+                ("Only supports TrailerFieldBC(1)");
+        }
+        int saltLen = params.getSaltLength();
+        if (this.p11Key != null) {
+            int maxSaltLen = ((this.p11Key.length() + 7) >> 3) - digestLen.intValue() - 2;
+
+            if (DEBUG) {
+                System.out.println("Max saltLen = " + maxSaltLen);
+                System.out.println("Curr saltLen = " + saltLen);
+            }
+            if (maxSaltLen < 0 || saltLen > maxSaltLen) {
+                throw new InvalidAlgorithmParameterException("Invalid with current key size");
+            }
+        } else {
+            if (DEBUG) System.out.println("No key available for validating saltLen");
+        }
+
+        // validated, now try to store the parameter internally
+        try {
+            this.mechanism.setParameter(
+                    new CK_RSA_PKCS_PSS_PARAMS(digestAlgorithm, "MGF1",
+                        digestAlgorithm, saltLen));
+            this.sigParams = params;
+        } catch (IllegalArgumentException iae) {
+            throw new InvalidAlgorithmParameterException(iae);
+        }
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineInitVerify(PublicKey publicKey)
+            throws InvalidKeyException {
+
+        if (publicKey == null) {
+            throw new InvalidKeyException("Key must not be null");
+        }
+
+        // Need to check key length whenever a new key is set
+        if (publicKey != p11Key) {
+            checkKeySize(publicKey);
+        }
+
+        reset(true);
+        mode = M_VERIFY;
+        p11Key = P11KeyFactory.convertKey(token, publicKey, KEY_ALGO);
+
+        // For PSS, defer PKCS11 initialization calls to update/doFinal as it
+        // needs both key and params
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineInitSign(PrivateKey privateKey)
+            throws InvalidKeyException {
+
+        if (privateKey == null) {
+            throw new InvalidKeyException("Key must not be null");
+        }
+
+        // Need to check RSA key length whenever a new key is set
+        if (privateKey != p11Key) {
+            checkKeySize(privateKey);
+        }
+
+        reset(true);
+        mode = M_SIGN;
+        p11Key = P11KeyFactory.convertKey(token, privateKey, KEY_ALGO);
+
+        // For PSS, defer PKCS11 initialization calls to update/doFinal as it
+        // needs both key and params
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineUpdate(byte b) throws SignatureException {
+        ensureInitialized();
+        isActive = true;
+        buffer[0] = b;
+        engineUpdate(buffer, 0, 1);
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineUpdate(byte[] b, int ofs, int len)
+            throws SignatureException {
+        ensureInitialized();
+        if (len == 0) {
+            return;
+        }
+        // check for overflow
+        if (len + bytesProcessed < 0) {
+            throw new ProviderException("Processed bytes limits exceeded.");
+        }
+        isActive = true;
+        switch (type) {
+        case T_UPDATE:
+            try {
+                if (mode == M_SIGN) {
+                    System.out.println(this + ": Calling C_SignUpdate");
+                    token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
+                } else {
+                    System.out.println(this + ": Calling C_VerfifyUpdate");
+                    token.p11.C_VerifyUpdate(session.id(), 0, b, ofs, len);
+                }
+                bytesProcessed += len;
+            } catch (PKCS11Exception e) {
+                reset(false);
+                throw new ProviderException(e);
+            }
+            break;
+        case T_DIGEST:
+            // should not happen as this should be covered by earlier checks
+            if (md == null) {
+                throw new ProviderException("PSS Parameters required");
+            }
+            md.update(b, ofs, len);
+            bytesProcessed += len;
+            break;
+        default:
+            throw new ProviderException("Internal error");
+        }
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineUpdate(ByteBuffer byteBuffer) {
+        try {
+            ensureInitialized();
+        } catch (SignatureException se) {
+            throw new ProviderException(se);
+        }
+        int len = byteBuffer.remaining();
+        if (len <= 0) {
+            return;
+        }
+        isActive = true;
+        switch (type) {
+        case T_UPDATE:
+            if (byteBuffer instanceof DirectBuffer == false) {
+                // cannot do better than default impl
+                super.engineUpdate(byteBuffer);
+                return;
+            }
+            long addr = ((DirectBuffer)byteBuffer).address();
+            int ofs = byteBuffer.position();
+            try {
+                if (mode == M_SIGN) {
+                    System.out.println(this + ": Calling C_SignUpdate");
+                    token.p11.C_SignUpdate
+                        (session.id(), addr + ofs, null, 0, len);
+                } else {
+                    System.out.println(this + ": Calling C_VerifyUpdate");
+                    token.p11.C_VerifyUpdate
+                        (session.id(), addr + ofs, null, 0, len);
+                }
+                bytesProcessed += len;
+                byteBuffer.position(ofs + len);
+            } catch (PKCS11Exception e) {
+                reset(false);
+                throw new ProviderException("Update failed", e);
+            }
+            break;
+        case T_DIGEST:
+            // should not happen as this should be covered by earlier checks
+            if (md == null) {
+                throw new ProviderException("PSS Parameters required");
+            }
+            md.update(byteBuffer);
+            bytesProcessed += len;
+            break;
+        default:
+            reset(false);
+            throw new ProviderException("Internal error");
+        }
+    }
+
+    // see JCA spec
+    @Override
+    protected byte[] engineSign() throws SignatureException {
+        ensureInitialized();
+        boolean doCancel = true;
+        if (DEBUG) System.out.print("Generating signature");
+        try {
+            byte[] signature;
+            if (type == T_UPDATE) {
+                if (DEBUG) System.out.println(" by C_SignFinal");
+                signature = token.p11.C_SignFinal(session.id(), 0);
+            } else {
+                if (md == null) {
+                    throw new ProviderException("PSS Parameters required");
+                }
+                byte[] digest = md.digest();
+                if (DEBUG) System.out.println(" by C_Sign");
+                signature = token.p11.C_Sign(session.id(), digest);
+            }
+            doCancel = false;
+            return signature;
+        } catch (PKCS11Exception pe) {
+            doCancel = false;
+            throw new ProviderException(pe);
+        } catch (ProviderException e) {
+            throw e;
+        } finally {
+            reset(doCancel);
+        }
+    }
+
+    // see JCA spec
+    @Override
+    protected boolean engineVerify(byte[] signature) throws SignatureException {
+        ensureInitialized();
+        boolean doCancel = true;
+        if (DEBUG) System.out.print("Verifying signature");
+        try {
+            if (type == T_UPDATE) {
+                if (DEBUG) System.out.println(" by C_VerifyFinal");
+                token.p11.C_VerifyFinal(session.id(), signature);
+            } else {
+                if (md == null) {
+                    throw new ProviderException("PSS Parameters required");
+                }
+                byte[] digest = md.digest();
+                if (DEBUG) System.out.println(" by C_Verify");
+                token.p11.C_Verify(session.id(), digest, signature);
+            }
+            doCancel = false;
+            return true;
+        } catch (PKCS11Exception pe) {
+            doCancel = false;
+            long errorCode = pe.getErrorCode();
+            if (errorCode == CKR_SIGNATURE_INVALID) {
+                return false;
+            }
+            if (errorCode == CKR_SIGNATURE_LEN_RANGE) {
+                // return false rather than throwing an exception
+                return false;
+            }
+            // ECF bug?
+            if (errorCode == CKR_DATA_LEN_RANGE) {
+                return false;
+            }
+            throw new ProviderException(pe);
+        }  catch (ProviderException e) {
+            throw e;
+        } finally {
+            reset(doCancel);
+        }
+    }
+
+    // see JCA spec
+    @SuppressWarnings("deprecation")
+    @Override
+    protected void engineSetParameter(String param, Object value)
+            throws InvalidParameterException {
+        throw new UnsupportedOperationException("setParameter() not supported");
+    }
+
+    // see JCA spec
+    @Override
+    protected void engineSetParameter(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+        // disallow changing parameters when update has been called
+        if (isActive) {
+            throw new ProviderException
+                ("Cannot set parameters during operations");
+        }
+        setSigParams(params);
+        if (type == T_DIGEST) {
+            try {
+                this.md = MessageDigest.getInstance(sigParams.getDigestAlgorithm());
+            } catch (NoSuchAlgorithmException nsae) {
+                throw new InvalidAlgorithmParameterException(nsae);
+            }
+        }
+    }
+
+    // see JCA spec
+    @SuppressWarnings("deprecation")
+    @Override
+    protected Object engineGetParameter(String param)
+            throws InvalidParameterException {
+        throw new UnsupportedOperationException("getParameter() not supported");
+    }
+
+    // see JCA spec
+    @Override
+    protected AlgorithmParameters engineGetParameters() {
+        if (this.sigParams != null) {
+            try {
+                AlgorithmParameters ap = AlgorithmParameters.getInstance("RSASSA-PSS");
+                ap.init(this.sigParams);
+                return ap;
+            } catch (GeneralSecurityException e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return null;
+    }
+}
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11RSACipher.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11RSACipher.java	Wed Jun 12 10:02:49 2019 +0530
@@ -275,10 +275,10 @@
                 long sessId = session.id();
                 switch (mode) {
                 case MODE_ENCRYPT:
-                    p11.C_Encrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
+                    p11.C_Encrypt(sessId, 0, buffer, 0, inLen, 0, buffer, 0, outLen);
                     break;
                 case MODE_DECRYPT:
-                    p11.C_Decrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
+                    p11.C_Decrypt(sessId, 0, buffer, 0, inLen, 0, buffer, 0, outLen);
                     break;
                 case MODE_SIGN:
                     byte[] tmpBuffer = new byte[maxInputSize];
@@ -372,11 +372,11 @@
             switch (mode) {
             case MODE_ENCRYPT:
                 n = p11.C_Encrypt
-                        (session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
+                        (session.id(), 0, buffer, 0, bufOfs, 0, out, outOfs, outLen);
                 break;
             case MODE_DECRYPT:
                 n = p11.C_Decrypt
-                        (session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
+                        (session.id(), 0, buffer, 0, bufOfs, 0, out, outOfs, outLen);
                 break;
             case MODE_SIGN:
                 byte[] tmpBuffer = new byte[bufOfs];
@@ -552,6 +552,7 @@
                     s = token.getObjSession();
                     long p11KeyType =
                         P11SecretKeyFactory.getPKCS11KeyType(algorithm);
+
                     CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
                             new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
                             new CK_ATTRIBUTE(CKA_KEY_TYPE, p11KeyType),
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -516,7 +516,9 @@
         String P11SecretKeyFactory = "sun.security.pkcs11.P11SecretKeyFactory";
         String P11Cipher           = "sun.security.pkcs11.P11Cipher";
         String P11RSACipher        = "sun.security.pkcs11.P11RSACipher";
+        String P11AEADCipher       = "sun.security.pkcs11.P11AEADCipher";
         String P11Signature        = "sun.security.pkcs11.P11Signature";
+        String P11PSSSignature     = "sun.security.pkcs11.P11PSSSignature";
 
         // XXX register all aliases
 
@@ -540,6 +542,12 @@
         d(MD, "SHA-512",        P11Digest,
                 s("2.16.840.1.101.3.4.2.3", "OID.2.16.840.1.101.3.4.2.3"),
                 m(CKM_SHA512));
+        d(MD, "SHA-512/224",        P11Digest,
+                s("2.16.840.1.101.3.4.2.5", "OID.2.16.840.1.101.3.4.2.5"),
+                m(CKM_SHA512_224));
+        d(MD, "SHA-512/256",        P11Digest,
+                s("2.16.840.1.101.3.4.2.6", "OID.2.16.840.1.101.3.4.2.6"),
+                m(CKM_SHA512_256));
 
         d(MAC, "HmacMD5",       P11MAC,
                 m(CKM_MD5_HMAC));
@@ -558,13 +566,22 @@
         d(MAC, "HmacSHA512",    P11MAC,
                 s("1.2.840.113549.2.11", "OID.1.2.840.113549.2.11"),
                 m(CKM_SHA512_HMAC));
+        d(MAC, "HmacSHA512/224",    P11MAC,
+                s("1.2.840.113549.2.12", "OID.1.2.840.113549.2.12"),
+                m(CKM_SHA512_224_HMAC));
+        d(MAC, "HmacSHA512/256",    P11MAC,
+                s("1.2.840.113549.2.13", "OID.1.2.840.113549.2.13"),
+                m(CKM_SHA512_256_HMAC));
+
         d(MAC, "SslMacMD5",     P11MAC,
                 m(CKM_SSL3_MD5_MAC));
         d(MAC, "SslMacSHA1",    P11MAC,
                 m(CKM_SSL3_SHA1_MAC));
 
         d(KPG, "RSA",           P11KeyPairGenerator,
+                s("1.2.840.113549.1.1", "OID.1.2.840.113549.1.1"),
                 m(CKM_RSA_PKCS_KEY_PAIR_GEN));
+
         d(KPG, "DSA",           P11KeyPairGenerator,
                 s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
                 m(CKM_DSA_KEY_PAIR_GEN));
@@ -587,6 +604,7 @@
         // register (Secret)KeyFactories if there are any mechanisms
         // for a particular algorithm that we support
         d(KF, "RSA",            P11RSAKeyFactory,
+                s("1.2.840.113549.1.1", "OID.1.2.840.113549.1.1"),
                 m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
         d(KF, "DSA",            P11DSAKeyFactory,
                 s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
@@ -600,10 +618,14 @@
         // AlgorithmParameters for EC.
         // Only needed until we have an EC implementation in the SUN provider.
         d(AGP, "EC",            "sun.security.util.ECParameters",
-                                                s("1.2.840.10045.2.1"),
+                s("1.2.840.10045.2.1"),
                 m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
                     CKM_ECDSA, CKM_ECDSA_SHA1));
 
+
+        d(AGP, "GCM",            "sun.security.util.GCMParameters",
+                m(CKM_AES_GCM));
+
         d(KA, "DH",             P11KeyAgreement,        s("DiffieHellman"),
                 m(CKM_DH_PKCS_DERIVE));
         d(KA, "ECDH",           "sun.security.pkcs11.P11ECDHKeyAgreement",
@@ -669,12 +691,24 @@
                 m(CKM_AES_ECB));
         d(CIP, "AES/CTR/NoPadding",             P11Cipher,
                 m(CKM_AES_CTR));
+
+        d(CIP, "AES/GCM/NoPadding",             P11AEADCipher,
+                m(CKM_AES_GCM));
+        d(CIP, "AES_128/GCM/NoPadding",          P11AEADCipher,
+                s("2.16.840.1.101.3.4.1.6", "OID.2.16.840.1.101.3.4.1.6"),
+                m(CKM_AES_GCM));
+        d(CIP, "AES_192/GCM/NoPadding",          P11AEADCipher,
+                s("2.16.840.1.101.3.4.1.26", "OID.2.16.840.1.101.3.4.1.26"),
+                m(CKM_AES_GCM));
+        d(CIP, "AES_256/GCM/NoPadding",          P11AEADCipher,
+                s("2.16.840.1.101.3.4.1.46", "OID.2.16.840.1.101.3.4.1.46"),
+                m(CKM_AES_GCM));
+
         d(CIP, "Blowfish/CBC/NoPadding",        P11Cipher,
                 m(CKM_BLOWFISH_CBC));
         d(CIP, "Blowfish/CBC/PKCS5Padding",     P11Cipher,
                 m(CKM_BLOWFISH_CBC));
 
-        // XXX RSA_X_509, RSA_OAEP not yet supported
         d(CIP, "RSA/ECB/PKCS1Padding",          P11RSACipher,   s("RSA"),
                 m(CKM_RSA_PKCS));
         d(CIP, "RSA/ECB/NoPadding",             P11RSACipher,
@@ -686,12 +720,25 @@
                 s("SHA1withDSA", "1.3.14.3.2.13", "1.3.14.3.2.27",
                   "1.2.840.10040.4.3", "OID.1.2.840.10040.4.3"),
                 m(CKM_DSA_SHA1, CKM_DSA));
+        d(SIG, "SHA224withDSA", P11Signature,
+                s("2.16.840.1.101.3.4.3.1", "OID.2.16.840.1.101.3.4.3.1"),
+                m(CKM_DSA_SHA224));
+        d(SIG, "SHA256withDSA", P11Signature,
+                s("2.16.840.1.101.3.4.3.2", "OID.2.16.840.1.101.3.4.3.2"),
+                m(CKM_DSA_SHA256));
+        d(SIG, "SHA384withDSA", P11Signature,
+                s("2.16.840.1.101.3.4.3.3", "OID.2.16.840.1.101.3.4.3.3"),
+                m(CKM_DSA_SHA384));
+        d(SIG, "SHA512withDSA", P11Signature,
+                s("2.16.840.1.101.3.4.3.4", "OID.2.16.840.1.101.3.4.3.4"),
+                m(CKM_DSA_SHA512));
         d(SIG, "RawDSAinP1363Format",   P11Signature,
                 s("NONEwithDSAinP1363Format"),
                 m(CKM_DSA));
         d(SIG, "DSAinP1363Format",      P11Signature,
                 s("SHA1withDSAinP1363Format"),
                 m(CKM_DSA_SHA1, CKM_DSA));
+
         d(SIG, "NONEwithECDSA", P11Signature,
                 m(CKM_ECDSA));
         d(SIG, "SHA1withECDSA", P11Signature,
@@ -743,6 +790,19 @@
         d(SIG, "SHA512withRSA", P11Signature,
                 s("1.2.840.113549.1.1.13", "OID.1.2.840.113549.1.1.13"),
                 m(CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
+        d(SIG, "RSASSA-PSS", P11PSSSignature,
+                s("1.2.840.113549.1.1.10", "OID.1.2.840.113549.1.1.10"),
+                m(CKM_RSA_PKCS_PSS));
+        d(SIG, "SHA1withRSASSA-PSS", P11PSSSignature,
+                m(CKM_SHA1_RSA_PKCS_PSS));
+        d(SIG, "SHA224withRSASSA-PSS", P11PSSSignature,
+                m(CKM_SHA224_RSA_PKCS_PSS));
+        d(SIG, "SHA256withRSASSA-PSS", P11PSSSignature,
+                m(CKM_SHA256_RSA_PKCS_PSS));
+        d(SIG, "SHA384withRSASSA-PSS", P11PSSSignature,
+                m(CKM_SHA384_RSA_PKCS_PSS));
+        d(SIG, "SHA512withRSASSA-PSS", P11PSSSignature,
+                m(CKM_SHA512_RSA_PKCS_PSS));
 
         d(KG, "SunTlsRsaPremasterSecret",
                     "sun.security.pkcs11.P11TlsRsaPremasterSecretGenerator",
@@ -1008,11 +1068,17 @@
             } else if (type == CIP) {
                 if (algorithm.startsWith("RSA")) {
                     return new P11RSACipher(token, algorithm, mechanism);
+                } else if (algorithm.endsWith("GCM/NoPadding")) {
+                    return new P11AEADCipher(token, algorithm, mechanism);
                 } else {
                     return new P11Cipher(token, algorithm, mechanism);
                 }
             } else if (type == SIG) {
-                return new P11Signature(token, algorithm, mechanism);
+                if (algorithm.indexOf("RSASSA-PSS") != -1) {
+                    return new P11PSSSignature(token, algorithm, mechanism);
+                } else {
+                    return new P11Signature(token, algorithm, mechanism);
+                }
             } else if (type == MAC) {
                 return new P11Mac(token, algorithm, mechanism);
             } else if (type == KPG) {
@@ -1051,7 +1117,14 @@
             } else if (type == KS) {
                 return token.getKeyStore();
             } else if (type == AGP) {
-                return new sun.security.util.ECParameters();
+                if (algorithm == "EC") {
+                    return new sun.security.util.ECParameters();
+                } else if (algorithm == "GCM") {
+                    return new sun.security.util.GCMParameters();
+                } else {
+                    throw new NoSuchAlgorithmException("Unsupported algorithm: "
+                            + algorithm);
+                }
             } else {
                 throw new NoSuchAlgorithmException("Unknown type: " + type);
             }
@@ -1070,7 +1143,7 @@
             String keyAlgorithm = key.getAlgorithm();
             // RSA signatures and cipher
             if (((type == CIP) && algorithm.startsWith("RSA"))
-                    || (type == SIG) && algorithm.endsWith("RSA")) {
+                    || (type == SIG) && (algorithm.indexOf("RSA") != -1)) {
                 if (keyAlgorithm.equals("RSA") == false) {
                     return false;
                 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_CCM_PARAMS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.pkcs11.wrapper;
+
+/**
+ * This class represents the necessary parameters required by
+ * the CKM_AES_CCM mechanism as defined in CK_CCM_PARAMS structure.<p>
+ * <B>PKCS#11 structure:</B>
+ * <PRE>
+ * typedef struct CK_CCM_PARAMS {
+ *   CK_ULONG ulDataLen;
+ *   CK_BYTE_PTR pNonce;
+ *   CK_ULONG ulNonceLen;
+ *   CK_BYTE_PTR pAAD;
+ *   CK_ULONG ulAADLen;
+ *   CK_ULONG ulMACLen;
+ * } CK_CCM_PARAMS;
+ * </PRE>
+ *
+ * @since   13
+ */
+public class CK_CCM_PARAMS {
+
+    private final long dataLen;
+    private final byte[] nonce;
+    private final byte[] aad;
+    private final long macLen;
+
+    public CK_CCM_PARAMS(int tagLen, byte[] iv, byte[] aad, int dataLen) {
+        this.dataLen = dataLen;
+        this.nonce = iv;
+        this.aad = aad;
+        this.macLen = tagLen;
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append(Constants.INDENT);
+        sb.append("ulDataLen: ");
+        sb.append(dataLen);
+        sb.append(Constants.NEWLINE);
+
+        sb.append(Constants.INDENT);
+        sb.append("iv: ");
+        sb.append(Functions.toHexString(nonce));
+        sb.append(Constants.NEWLINE);
+
+        sb.append(Constants.INDENT);
+        sb.append("aad: ");
+        sb.append(Functions.toHexString(aad));
+        sb.append(Constants.NEWLINE);
+
+        sb.append(Constants.INDENT);
+        sb.append("tagLen: ");
+        sb.append(macLen);
+
+        return sb.toString();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_GCM_PARAMS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.pkcs11.wrapper;
+
+/**
+ * This class represents the necessary parameters required by
+ * the CKM_AES_GCM mechanism as defined in CK_GCM_PARAMS structure.<p>
+ * <B>PKCS#11 structure:</B>
+ * <PRE>
+ * typedef struct CK_GCM_PARAMS {
+ *    CK_BYTE_PTR       pIv;
+ *    CK_ULONG          ulIvLen;
+ *    CK_BYTE_PTR       pAAD;
+ *    CK_ULONG          ulAADLen;
+ *    CK_ULONG          ulTagBits;
+ * } CK_GCM_PARAMS;
+ * </PRE>
+ *
+ * @since   10
+ */
+public class CK_GCM_PARAMS {
+
+    private final byte[] iv;
+    private final byte[] aad;
+    private final long tagBits;
+
+    public CK_GCM_PARAMS(int tagLenInBits, byte[] iv, byte[] aad) {
+        this.iv = iv;
+        this.aad = aad;
+        this.tagBits = tagLenInBits;
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append(Constants.INDENT);
+        sb.append("iv: ");
+        sb.append(Functions.toHexString(iv));
+        sb.append(Constants.NEWLINE);
+
+        sb.append(Constants.INDENT);
+        sb.append("aad: ");
+        sb.append(Functions.toHexString(aad));
+        sb.append(Constants.NEWLINE);
+
+        sb.append(Constants.INDENT);
+        sb.append("tagLen(in bits): ");
+        sb.append(tagBits);
+
+        return sb.toString();
+    }
+}
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -82,11 +82,15 @@
      *   CK_ULONG ulParameterLen;
      * </PRE>
      */
-    public Object pParameter;
+    public Object pParameter = null;
 
-    public CK_MECHANISM() {
-        // empty
-    }
+    // pointer to native CK_MECHANISM structure
+    // For mechanisms which have only mechanism id, the native structure
+    // can be freed right after init and this field will not be used. However,
+    // for mechanisms which have both mechanism id and parameters, it can
+    // only be freed after operation is finished. Thus, the native pointer
+    // will be stored here and then be explicitly freed by caller.
+    private long pHandle = 0L;
 
     public CK_MECHANISM(long mechanism) {
         this.mechanism = mechanism;
@@ -95,7 +99,6 @@
     // We don't have a (long,Object) constructor to force type checking.
     // This makes sure we don't accidentally pass a class that the native
     // code cannot handle.
-
     public CK_MECHANISM(long mechanism, byte[] pParameter) {
         init(mechanism, pParameter);
     }
@@ -144,6 +147,33 @@
         init(mechanism, params);
     }
 
+    public CK_MECHANISM(long mechanism, CK_GCM_PARAMS params) {
+        init(mechanism, params);
+    }
+
+    public CK_MECHANISM(long mechanism, CK_CCM_PARAMS params) {
+        init(mechanism, params);
+    }
+
+    // For PSS. the parameter may be set multiple times, use the
+    // CK_MECHANISM(long) constructor and setParameter(CK_RSA_PKCS_PSS_PARAMS)
+    // methods instead of creating yet another constructor
+    public void setParameter(CK_RSA_PKCS_PSS_PARAMS params) {
+        assert(this.mechanism == CKM_RSA_PKCS_PSS);
+        assert(params != null);
+        if (this.pParameter != null && this.pParameter.equals(params)) {
+            return;
+        }
+        freeHandle();
+        this.pParameter = params;
+    }
+
+    public void freeHandle() {
+        if (this.pHandle != 0L) {
+            this.pHandle = PKCS11.freeMechanism(pHandle);
+        }
+    }
+
     private void init(long mechanism, Object pParameter) {
         this.mechanism = mechanism;
         this.pParameter = pParameter;
@@ -167,12 +197,17 @@
         sb.append(pParameter.toString());
         sb.append(Constants.NEWLINE);
 
+        /*
         sb.append(Constants.INDENT);
         sb.append("ulParameterLen: ??");
-        //buffer.append(pParameter.length);
-        //buffer.append(Constants.NEWLINE);
-
+        sb.append(Constants.NEWLINE);
+        */
+        if (pHandle != 0L) {
+            sb.append(Constants.INDENT);
+            sb.append("pHandle: ");
+            sb.append(pHandle);
+            sb.append(Constants.NEWLINE);
+        }
         return sb.toString() ;
     }
-
 }
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,118 +1,105 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
- *
- * Redistribution and use in  source and binary forms, with or without
- * modification, are permitted  provided that the following conditions are met:
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
- * 1. Redistributions of  source code must retain the above copyright notice,
- *    this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in  binary form must reproduce the above copyright notice,
- *    this list of conditions and the following disclaimer in the documentation
- *    and/or other materials provided with the distribution.
- *
- * 3. The end-user documentation included with the redistribution, if any, must
- *    include the following acknowledgment:
- *
- *    "This product includes software developed by IAIK of Graz University of
- *     Technology."
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
  *
- *    Alternately, this acknowledgment may appear in the software itself, if
- *    and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Graz University of Technology" and "IAIK of Graz University of
- *    Technology" must not be used to endorse or promote products derived from
- *    this software without prior written permission.
- *
- * 5. Products derived from this software may not be called
- *    "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior
- *    written permission of Graz University of Technology.
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
  *
- *  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
- *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
- *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- *  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- *  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- *  POSSIBILITY  OF SUCH DAMAGE.
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
  */
 
 package sun.security.pkcs11.wrapper;
 
+import java.security.ProviderException;
+import java.security.spec.PSSParameterSpec;
+import java.security.spec.MGF1ParameterSpec;
 
 
 /**
- * class CK_RSA_PKCS_PSS_PARAMS provides the parameters to the CKM_RSA_PKCS_OAEP
- * mechanism.<p>
+ * This class represents the necessary parameters required by the
+ * CKM_RSA_PKCS_PSS mechanism as defined in CK_RSA_PKCS_PSS_PARAMS structure.<p>
  * <B>PKCS#11 structure:</B>
  * <PRE>
  * typedef struct CK_RSA_PKCS_PSS_PARAMS {
- *   CK_MECHANISM_TYPE hashAlg;
- *   CK_RSA_PKCS_MGF_TYPE mgf;
- *   CK_ULONG sLen;
+ *    CK_MECHANISM_TYPE    hashAlg;
+ *    CK_RSA_PKCS_MGF_TYPE mgf;
+ *    CK_ULONG             sLen;
  * } CK_RSA_PKCS_PSS_PARAMS;
  * </PRE>
  *
- * @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
+ * @since   13
  */
 public class CK_RSA_PKCS_PSS_PARAMS {
 
-    /**
-     * <B>PKCS#11:</B>
-     * <PRE>
-     *   CK_MECHANISM_TYPE hashAlg;
-     * </PRE>
-     */
-    public long hashAlg;
+    private final long hashAlg;
+    private final long mgf;
+    private final long sLen;
+
+    public CK_RSA_PKCS_PSS_PARAMS(String hashAlg, String mgfAlg,
+            String mgfHash, int sLen) {
+        this.hashAlg = Functions.getHashMechId(hashAlg);
+        if (!mgfAlg.equals("MGF1")) {
+            throw new ProviderException("Only MGF1 is supported");
+        }
+        // no dash in PKCS#11 mechanism names
+        this.mgf = Functions.getMGFId("CKG_MGF1_" + hashAlg.replaceFirst("-", ""));
+        this.sLen = sLen;
+    }
 
-    /**
-     * <B>PKCS#11:</B>
-     * <PRE>
-     *   CK_RSA_PKCS_MGF_TYPE mgf;
-     * </PRE>
-     */
-    public long mgf;
+    @Override
+    public boolean equals(Object o) {
+        if (o == this) {
+            return true;
+        }
+
+        if (!(o instanceof CK_RSA_PKCS_PSS_PARAMS)) {
+            return false;
+        }
 
-    /**
-     * <B>PKCS#11:</B>
-     * <PRE>
-     *   CK_ULONG sLen;
-     * </PRE>
-     */
-    public long sLen;
+        CK_RSA_PKCS_PSS_PARAMS other = (CK_RSA_PKCS_PSS_PARAMS) o;
+        return ((other.hashAlg == hashAlg) &&
+                (other.mgf == mgf) &&
+                (other.sLen == sLen));
+    }
 
-    /**
-     * Returns the string representation of CK_PKCS5_PBKD2_PARAMS.
-     *
-     * @return the string representation of CK_PKCS5_PBKD2_PARAMS
-     */
+    @Override
+    public int hashCode() {
+        return (int)(hashAlg << 2 + mgf << 1 + sLen);
+    }
+
+    @Override
     public String toString() {
         StringBuilder sb = new StringBuilder();
 
         sb.append(Constants.INDENT);
-        sb.append("hashAlg: 0x");
+        sb.append("hashAlg: ");
         sb.append(Functions.toFullHexString(hashAlg));
         sb.append(Constants.NEWLINE);
 
         sb.append(Constants.INDENT);
-        sb.append("mgf: 0x");
+        sb.append("mgf: ");
         sb.append(Functions.toFullHexString(mgf));
         sb.append(Constants.NEWLINE);
 
         sb.append(Constants.INDENT);
-        sb.append("sLen: ");
+        sb.append("sLen(in bytes): ");
         sb.append(sLen);
-        //buffer.append(Constants.NEWLINE);
 
         return sb.toString();
     }
-
 }
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/Functions.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/Functions.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -97,6 +97,13 @@
     private static final Map<String,Integer> objectClassIds =
         new HashMap<String,Integer>();
 
+    // MGFs (CKG_*)
+    private static final Map<Integer,String> mgfNames =
+        new HashMap<Integer,String>();
+
+    private static final Map<String,Integer> mgfIds =
+        new HashMap<String,Integer>();
+
     /**
      * For converting numbers to their hex presentation.
      */
@@ -401,7 +408,11 @@
             name = nameMap.get(Integer.valueOf((int)id));
         }
         if (name == null) {
-            name = "Unknown 0x" + toFullHexString(id);
+            if ((id & CKM_VENDOR_DEFINED) != 0) {
+                name = "(Vendor-Specific) 0x" + toFullHexString(id);
+            } else {
+                name = "(Unknown) 0x" + toFullHexString(id);
+            }
         }
         return name;
     }
@@ -450,6 +461,14 @@
         return hashMechIds.get(name);
     }
 
+    public static String getMGFName(long id) {
+        return getName(mgfNames, id);
+    }
+
+    public static long getMGFId(String name) {
+        return getId(mgfIds, name);
+    }
+
     /**
      * Check the given arrays for equalitiy. This method considers both arrays as
      * equal, if both are <code>null</code> or both have the same length and
@@ -595,8 +614,14 @@
         addMapping(objectClassNames, objectClassIds, id, name);
     }
 
-    private static void addHashMech(long id, String name) {
-        hashMechIds.put(name, id);
+    private static void addHashMech(long id, String... names) {
+        for (String n : names) {
+            hashMechIds.put(n, id);
+        }
+    }
+
+    private static void addMGF(long id, String name) {
+        addMapping(mgfNames, mgfIds, id, name);
     }
 
     static {
@@ -618,16 +643,27 @@
         addMech(CKM_DSA_KEY_PAIR_GEN,           "CKM_DSA_KEY_PAIR_GEN");
         addMech(CKM_DSA,                        "CKM_DSA");
         addMech(CKM_DSA_SHA1,                   "CKM_DSA_SHA1");
+        addMech(CKM_DSA_SHA224,                 "CKM_DSA_SHA224");
+        addMech(CKM_DSA_SHA256,                 "CKM_DSA_SHA256");
+        addMech(CKM_DSA_SHA384,                 "CKM_DSA_SHA384");
+        addMech(CKM_DSA_SHA512,                 "CKM_DSA_SHA512");
+
         addMech(CKM_DH_PKCS_KEY_PAIR_GEN,       "CKM_DH_PKCS_KEY_PAIR_GEN");
         addMech(CKM_DH_PKCS_DERIVE,             "CKM_DH_PKCS_DERIVE");
         addMech(CKM_X9_42_DH_KEY_PAIR_GEN,      "CKM_X9_42_DH_KEY_PAIR_GEN");
         addMech(CKM_X9_42_DH_DERIVE,            "CKM_X9_42_DH_DERIVE");
         addMech(CKM_X9_42_DH_HYBRID_DERIVE,     "CKM_X9_42_DH_HYBRID_DERIVE");
         addMech(CKM_X9_42_MQV_DERIVE,           "CKM_X9_42_MQV_DERIVE");
-        addMech(CKM_SHA224_RSA_PKCS,            "CKM_SHA224_RSA_PKCS");
+
         addMech(CKM_SHA256_RSA_PKCS,            "CKM_SHA256_RSA_PKCS");
         addMech(CKM_SHA384_RSA_PKCS,            "CKM_SHA384_RSA_PKCS");
         addMech(CKM_SHA512_RSA_PKCS,            "CKM_SHA512_RSA_PKCS");
+        addMech(CKM_SHA256_RSA_PKCS_PSS,        "CKM_SHA256_RSA_PKCS_PSS");
+        addMech(CKM_SHA384_RSA_PKCS_PSS,        "CKM_SHA384_RSA_PKCS_PSS");
+        addMech(CKM_SHA512_RSA_PKCS_PSS,        "CKM_SHA512_RSA_PKCS_PSS");
+        addMech(CKM_SHA224_RSA_PKCS,            "CKM_SHA224_RSA_PKCS");
+        addMech(CKM_SHA224_RSA_PKCS_PSS,        "CKM_SHA224_RSA_PKCS_PSS");
+
         addMech(CKM_RC2_KEY_GEN,                "CKM_RC2_KEY_GEN");
         addMech(CKM_RC2_ECB,                    "CKM_RC2_ECB");
         addMech(CKM_RC2_CBC,                    "CKM_RC2_CBC");
@@ -649,12 +685,21 @@
         addMech(CKM_DES3_MAC,                   "CKM_DES3_MAC");
         addMech(CKM_DES3_MAC_GENERAL,           "CKM_DES3_MAC_GENERAL");
         addMech(CKM_DES3_CBC_PAD,               "CKM_DES3_CBC_PAD");
+        addMech(CKM_DES3_CMAC_GENERAL,          "CKM_DES3_CMAC_GENERAL");
+        addMech(CKM_DES3_CMAC,                  "CKM_DES3_CMAC");
+
         addMech(CKM_CDMF_KEY_GEN,               "CKM_CDMF_KEY_GEN");
         addMech(CKM_CDMF_ECB,                   "CKM_CDMF_ECB");
         addMech(CKM_CDMF_CBC,                   "CKM_CDMF_CBC");
         addMech(CKM_CDMF_MAC,                   "CKM_CDMF_MAC");
         addMech(CKM_CDMF_MAC_GENERAL,           "CKM_CDMF_MAC_GENERAL");
         addMech(CKM_CDMF_CBC_PAD,               "CKM_CDMF_CBC_PAD");
+
+        addMech(CKM_DES_OFB64,                  "CKM_DES_OFB64");
+        addMech(CKM_DES_OFB8,                   "CKM_DES_OFB8");
+        addMech(CKM_DES_CFB64,                  "CKM_DES_CFB64");
+        addMech(CKM_DES_CFB8,                   "CKM_DES_CFB8");
+
         addMech(CKM_MD2,                        "CKM_MD2");
         addMech(CKM_MD2_HMAC,                   "CKM_MD2_HMAC");
         addMech(CKM_MD2_HMAC_GENERAL,           "CKM_MD2_HMAC_GENERAL");
@@ -682,6 +727,26 @@
         addMech(CKM_SHA512,                     "CKM_SHA512");
         addMech(CKM_SHA512_HMAC,                "CKM_SHA512_HMAC");
         addMech(CKM_SHA512_HMAC_GENERAL,        "CKM_SHA512_HMAC_GENERAL");
+        addMech(CKM_SHA512_224,                 "CKM_SHA512_224");
+        addMech(CKM_SHA512_224_HMAC,            "CKM_SHA512_224_HMAC");
+        addMech(CKM_SHA512_224_HMAC_GENERAL,    "CKM_SHA512_224_HMAC_GENERAL");
+        addMech(CKM_SHA512_224_KEY_DERIVATION,  "CKM_SHA512_224_KEY_DERIVATION");
+        addMech(CKM_SHA512_256,                 "CKM_SHA512_256");
+        addMech(CKM_SHA512_256_HMAC,            "CKM_SHA512_256_HMAC");
+        addMech(CKM_SHA512_256_HMAC_GENERAL,    "CKM_SHA512_256_HMAC_GENERAL");
+        addMech(CKM_SHA512_256_KEY_DERIVATION,  "CKM_SHA512_256_KEY_DERIVATION");
+        addMech(CKM_SHA512_T,                   "CKM_SHA512_T");
+        addMech(CKM_SHA512_T_HMAC,              "CKM_SHA512_T_HMAC");
+        addMech(CKM_SHA512_T_HMAC_GENERAL,      "CKM_SHA512_T_HMAC_GENERAL");
+        addMech(CKM_SHA512_T_KEY_DERIVATION,    "CKM_SHA512_T_KEY_DERIVATION");
+
+        addMech(CKM_SECURID_KEY_GEN,            "CKM_SECURID_KEY_GEN");
+        addMech(CKM_SECURID,                    "CKM_SECURID");
+        addMech(CKM_HOTP_KEY_GEN,               "CKM_HOTP_KEY_GEN");
+        addMech(CKM_HOTP,                       "CKM_HOTP");
+        addMech(CKM_ACTI,                       "CKM_ACTI");
+        addMech(CKM_ACTI_KEY_GEN,               "CKM_ACTI_KEY_GEN");
+
         addMech(CKM_CAST_KEY_GEN,               "CKM_CAST_KEY_GEN");
         addMech(CKM_CAST_ECB,                   "CKM_CAST_ECB");
         addMech(CKM_CAST_CBC,                   "CKM_CAST_CBC");
@@ -729,10 +794,7 @@
         addMech(CKM_TLS_PRF,                    "CKM_TLS_PRF");
         addMech(CKM_SSL3_MD5_MAC,               "CKM_SSL3_MD5_MAC");
         addMech(CKM_SSL3_SHA1_MAC,              "CKM_SSL3_SHA1_MAC");
-        addMech(CKM_TLS12_MASTER_KEY_DERIVE,    "CKM_TLS12_MASTER_KEY_DERIVE");
-        addMech(CKM_TLS12_KEY_AND_MAC_DERIVE,   "CKM_TLS12_KEY_AND_MAC_DERIVE");
-        addMech(CKM_TLS12_MASTER_KEY_DERIVE_DH, "CKM_TLS12_MASTER_KEY_DERIVE_DH");
-        addMech(CKM_TLS_MAC,                    "CKM_TLS_MAC");
+
         addMech(CKM_MD5_KEY_DERIVATION,         "CKM_MD5_KEY_DERIVATION");
         addMech(CKM_MD2_KEY_DERIVATION,         "CKM_MD2_KEY_DERIVATION");
         addMech(CKM_SHA1_KEY_DERIVATION,        "CKM_SHA1_KEY_DERIVATION");
@@ -754,8 +816,62 @@
         addMech(CKM_PBE_SHA1_RC2_40_CBC,        "CKM_PBE_SHA1_RC2_40_CBC");
         addMech(CKM_PKCS5_PBKD2,                "CKM_PKCS5_PBKD2");
         addMech(CKM_PBA_SHA1_WITH_SHA1_HMAC,    "CKM_PBA_SHA1_WITH_SHA1_HMAC");
+
+        addMech(CKM_WTLS_PRE_MASTER_KEY_GEN,    "CKM_WTLS_PRE_MASTER_KEY_GEN");
+        addMech(CKM_WTLS_MASTER_KEY_DERIVE,     "CKM_WTLS_MASTER_KEY_DERIVE");
+        addMech(CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC,
+                                                "CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC");
+        addMech(CKM_WTLS_PRF,                   "CKM_WTLS_PRF");
+        addMech(CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE,
+                                                "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE");
+        addMech(CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE,
+                                                "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE");
+        addMech(CKM_TLS10_MAC_SERVER,           "CKM_TLS10_MAC_SERVER");
+        addMech(CKM_TLS10_MAC_CLIENT,           "CKM_TLS10_MAC_CLIENT");
+        addMech(CKM_TLS12_MAC,                  "CKM_TLS12_MAC");
+        addMech(CKM_TLS12_KDF,                  "CKM_TLS12_KDF");
+        addMech(CKM_TLS12_MASTER_KEY_DERIVE,    "CKM_TLS12_MASTER_KEY_DERIVE");
+        addMech(CKM_TLS12_KEY_AND_MAC_DERIVE,   "CKM_TLS12_KEY_AND_MAC_DERIVE");
+        addMech(CKM_TLS12_MASTER_KEY_DERIVE_DH, "CKM_TLS12_MASTER_KEY_DERIVE_DH");
+        addMech(CKM_TLS12_KEY_SAFE_DERIVE,      "CKM_TLS12_KEY_SAFE_DERIVE");
+        addMech(CKM_TLS_MAC,                    "CKM_TLS_MAC");
+        addMech(CKM_TLS_KDF,                    "CKM_TLS_KDF");
+
         addMech(CKM_KEY_WRAP_LYNKS,             "CKM_KEY_WRAP_LYNKS");
         addMech(CKM_KEY_WRAP_SET_OAEP,          "CKM_KEY_WRAP_SET_OAEP");
+
+        addMech(CKM_CMS_SIG,                    "CKM_CMS_SIG");
+        addMech(CKM_KIP_DERIVE,                 "CKM_KIP_DERIVE");
+        addMech(CKM_KIP_WRAP,                   "CKM_KIP_WRAP");
+        addMech(CKM_KIP_MAC,                    "CKM_KIP_MAC");
+        addMech(CKM_CAMELLIA_KEY_GEN,           "CKM_CAMELLIA_KEY_GEN");
+        addMech(CKM_CAMELLIA_ECB,               "CKM_CAMELLIA_ECB");
+        addMech(CKM_CAMELLIA_CBC,               "CKM_CAMELLIA_CBC");
+        addMech(CKM_CAMELLIA_MAC,               "CKM_CAMELLIA_MAC");
+        addMech(CKM_CAMELLIA_MAC_GENERAL,       "CKM_CAMELLIA_MAC_GENERAL");
+        addMech(CKM_CAMELLIA_CBC_PAD,           "CKM_CAMELLIA_CBC_PAD");
+        addMech(CKM_CAMELLIA_ECB_ENCRYPT_DATA,  "CKM_CAMELLIA_ECB_ENCRYPT_DATA");
+        addMech(CKM_CAMELLIA_CBC_ENCRYPT_DATA,  "CKM_CAMELLIA_CBC_ENCRYPT_DATA");
+        addMech(CKM_CAMELLIA_CTR,               "CKM_CAMELLIA_CTR");
+
+        addMech(CKM_ARIA_KEY_GEN,               "CKM_ARIA_KEY_GEN");
+        addMech(CKM_ARIA_ECB,                   "CKM_ARIA_ECB");
+        addMech(CKM_ARIA_CBC,                   "CKM_ARIA_CBC");
+        addMech(CKM_ARIA_MAC,                   "CKM_ARIA_MAC");
+        addMech(CKM_ARIA_MAC_GENERAL,           "CKM_ARIA_MAC_GENERAL");
+        addMech(CKM_ARIA_CBC_PAD,               "CKM_ARIA_CBC_PAD");
+        addMech(CKM_ARIA_ECB_ENCRYPT_DATA,      "CKM_ARIA_ECB_ENCRYPT_DATA");
+        addMech(CKM_ARIA_CBC_ENCRYPT_DATA,      "CKM_ARIA_CBC_ENCRYPT_DATA");
+
+        addMech(CKM_SEED_KEY_GEN,               "CKM_SEED_KEY_GEN");
+        addMech(CKM_SEED_ECB,                   "CKM_SEED_ECB");
+        addMech(CKM_SEED_CBC,                   "CKM_SEED_CBC");
+        addMech(CKM_SEED_MAC,                   "CKM_SEED_MAC");
+        addMech(CKM_SEED_MAC_GENERAL,           "CKM_SEED_MAC_GENERAL");
+        addMech(CKM_SEED_CBC_PAD,               "CKM_SEED_CBC_PAD");
+        addMech(CKM_SEED_ECB_ENCRYPT_DATA,      "CKM_SEED_ECB_ENCRYPT_DATA");
+        addMech(CKM_SEED_CBC_ENCRYPT_DATA,      "CKM_SEED_CBC_ENCRYPT_DATA");
+
         addMech(CKM_SKIPJACK_KEY_GEN,           "CKM_SKIPJACK_KEY_GEN");
         addMech(CKM_SKIPJACK_ECB64,             "CKM_SKIPJACK_ECB64");
         addMech(CKM_SKIPJACK_CBC64,             "CKM_SKIPJACK_CBC64");
@@ -780,9 +896,17 @@
         addMech(CKM_EC_KEY_PAIR_GEN,            "CKM_EC_KEY_PAIR_GEN");
         addMech(CKM_ECDSA,                      "CKM_ECDSA");
         addMech(CKM_ECDSA_SHA1,                 "CKM_ECDSA_SHA1");
+        addMech(CKM_ECDSA_SHA224,               "CKM_ECDSA_SHA224");
+        addMech(CKM_ECDSA_SHA256,               "CKM_ECDSA_SHA256");
+        addMech(CKM_ECDSA_SHA384,               "CKM_ECDSA_SHA384");
+        addMech(CKM_ECDSA_SHA512,               "CKM_ECDSA_SHA512");
+
         addMech(CKM_ECDH1_DERIVE,               "CKM_ECDH1_DERIVE");
         addMech(CKM_ECDH1_COFACTOR_DERIVE,      "CKM_ECDH1_COFACTOR_DERIVE");
         addMech(CKM_ECMQV_DERIVE,               "CKM_ECMQV_DERIVE");
+        addMech(CKM_ECDH_AES_KEY_WRAP,          "CKM_ECDH_AES_KEY_WRAP");
+        addMech(CKM_RSA_AES_KEY_WRAP,           "CKM_RSA_AES_KEY_WRAP");
+
         addMech(CKM_JUNIPER_KEY_GEN,            "CKM_JUNIPER_KEY_GEN");
         addMech(CKM_JUNIPER_ECB128,             "CKM_JUNIPER_ECB128");
         addMech(CKM_JUNIPER_CBC128,             "CKM_JUNIPER_CBC128");
@@ -796,11 +920,61 @@
         addMech(CKM_AES_MAC,                    "CKM_AES_MAC");
         addMech(CKM_AES_MAC_GENERAL,            "CKM_AES_MAC_GENERAL");
         addMech(CKM_AES_CBC_PAD,                "CKM_AES_CBC_PAD");
+        addMech(CKM_AES_CTR,                    "CKM_AES_CTR");
+        addMech(CKM_AES_GCM,                    "CKM_AES_GCM");
+        addMech(CKM_AES_CCM,                    "CKM_AES_CCM");
+        addMech(CKM_AES_CTS,                    "CKM_AES_CTS");
+        addMech(CKM_AES_CMAC,                   "CKM_AES_CMAC");
+        addMech(CKM_AES_CMAC_GENERAL,           "CKM_AES_CMAC_GENERAL");
+        addMech(CKM_AES_XCBC_MAC,               "CKM_AES_XCBC_MAC");
+        addMech(CKM_AES_XCBC_MAC_96,            "CKM_AES_XCBC_MAC_96");
+        addMech(CKM_AES_GMAC,                   "CKM_AES_GMAC");
+
         addMech(CKM_BLOWFISH_KEY_GEN,           "CKM_BLOWFISH_KEY_GEN");
         addMech(CKM_BLOWFISH_CBC,               "CKM_BLOWFISH_CBC");
+        addMech(CKM_TWOFISH_KEY_GEN,            "CKM_TWOFISH_KEY_GEN");
+        addMech(CKM_TWOFISH_CBC,                "CKM_TWOFISH_CBC");
+        addMech(CKM_BLOWFISH_CBC_PAD,           "CKM_BLOWFISH_CBC_PAD");
+        addMech(CKM_TWOFISH_CBC_PAD,            "CKM_TWOFISH_CBC_PAD");
+
+        addMech(CKM_DES_ECB_ENCRYPT_DATA,       "CKM_DES_ECB_ENCRYPT_DATA");
+        addMech(CKM_DES_CBC_ENCRYPT_DATA,       "CKM_DES_CBC_ENCRYPT_DATA");
+        addMech(CKM_DES3_ECB_ENCRYPT_DATA,      "CKM_DES3_ECB_ENCRYPT_DATA");
+        addMech(CKM_DES3_CBC_ENCRYPT_DATA,      "CKM_DES3_CBC_ENCRYPT_DATA");
+        addMech(CKM_AES_ECB_ENCRYPT_DATA,       "CKM_AES_ECB_ENCRYPT_DATA");
+        addMech(CKM_AES_CBC_ENCRYPT_DATA,       "CKM_AES_CBC_ENCRYPT_DATA");
+
+        addMech(CKM_GOSTR3410_KEY_PAIR_GEN,     "CKM_GOSTR3410_KEY_PAIR_GEN");
+        addMech(CKM_GOSTR3410,                  "CKM_GOSTR3410");
+        addMech(CKM_GOSTR3410_WITH_GOSTR3411,   "CKM_GOSTR3410_WITH_GOSTR3411");
+        addMech(CKM_GOSTR3410_KEY_WRAP,         "CKM_GOSTR3410_KEY_WRAP");
+        addMech(CKM_GOSTR3410_DERIVE,           "CKM_GOSTR3410_DERIVE");
+        addMech(CKM_GOSTR3411,                  "CKM_GOSTR3411");
+        addMech(CKM_GOSTR3411_HMAC,             "CKM_GOSTR3411_HMAC");
+        addMech(CKM_GOST28147_KEY_GEN,          "CKM_GOST28147_KEY_GEN");
+        addMech(CKM_GOST28147_ECB,              "CKM_GOST28147_ECB");
+        addMech(CKM_GOST28147,                  "CKM_GOST28147");
+        addMech(CKM_GOST28147_MAC,              "CKM_GOST28147_MAC");
+        addMech(CKM_GOST28147_KEY_WRAP,         "CKM_GOST28147_KEY_WRAP");
+
         addMech(CKM_DSA_PARAMETER_GEN,          "CKM_DSA_PARAMETER_GEN");
         addMech(CKM_DH_PKCS_PARAMETER_GEN,      "CKM_DH_PKCS_PARAMETER_GEN");
         addMech(CKM_X9_42_DH_PARAMETER_GEN,     "CKM_X9_42_DH_PARAMETER_GEN");
+        addMech(CKM_DSA_PROBABLISTIC_PARAMETER_GEN,
+                                                "CKM_DSA_PROBABLISTIC_PARAMETER_GEN");
+        addMech(CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN,
+                                                "CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN");
+        addMech(CKM_AES_OFB,                    "CKM_AES_OFB");
+        addMech(CKM_AES_CFB64,                  "CKM_AES_CFB64");
+        addMech(CKM_AES_CFB8,                   "CKM_AES_CFB8");
+        addMech(CKM_AES_CFB128,                 "CKM_AES_CFB128");
+        addMech(CKM_AES_CFB1,                   "CKM_AES_CFB1");
+        addMech(CKM_AES_KEY_WRAP,               "CKM_AES_KEY_WRAP");
+        addMech(CKM_AES_KEY_WRAP_PAD,           "CKM_AES_KEY_WRAP_PAD");
+
+        addMech(CKM_RSA_PKCS_TPM_1_1,           "CKM_RSA_PKCS_TPM_1_1");
+        addMech(CKM_RSA_PKCS_OAEP_TPM_1_1,      "CKM_RSA_PKCS_OAEP_TPM_1_1");
+
         addMech(CKM_VENDOR_DEFINED,             "CKM_VENDOR_DEFINED");
 
         addMech(CKM_NSS_TLS_PRF_GENERAL,        "CKM_NSS_TLS_PRF_GENERAL");
@@ -808,11 +982,13 @@
         addMech(PCKM_SECURERANDOM,              "SecureRandom");
         addMech(PCKM_KEYSTORE,                  "KeyStore");
 
-        addHashMech(CKM_SHA_1, "SHA-1");
-        addHashMech(CKM_SHA224, "SHA-224");
-        addHashMech(CKM_SHA256, "SHA-256");
-        addHashMech(CKM_SHA384, "SHA-384");
-        addHashMech(CKM_SHA512, "SHA-512");
+        addHashMech(CKM_SHA_1,                  "SHA-1", "SHA", "SHA1");
+        addHashMech(CKM_SHA224,                 "SHA-224", "SHA224");
+        addHashMech(CKM_SHA256,                 "SHA-256", "SHA256");
+        addHashMech(CKM_SHA384,                 "SHA-384", "SHA384");
+        addHashMech(CKM_SHA512,                 "SHA-512", "SHA512");
+        addHashMech(CKM_SHA512_224,             "SHA-512/224", "SHA512/224");
+        addHashMech(CKM_SHA512_256,             "SHA-512/256", "SHA512/256");
 
         addKeyType(CKK_RSA,                     "CKK_RSA");
         addKeyType(CKK_DSA,                     "CKK_DSA");
@@ -837,6 +1013,25 @@
         addKeyType(CKK_CDMF,                    "CKK_CDMF");
         addKeyType(CKK_AES,                     "CKK_AES");
         addKeyType(CKK_BLOWFISH,                "CKK_BLOWFISH");
+        addKeyType(CKK_TWOFISH,                 "CKK_TWOFISH");
+        addKeyType(CKK_SECURID,                 "CKK_SECURID");
+        addKeyType(CKK_HOTP,                    "CKK_HOTP");
+        addKeyType(CKK_ACTI,                    "CKK_ACTI");
+        addKeyType(CKK_CAMELLIA,                "CKK_CAMELLIA");
+        addKeyType(CKK_ARIA,                    "CKK_ARIA");
+        addKeyType(CKK_MD5_HMAC,                "CKK_MD5_HMAC");
+        addKeyType(CKK_SHA_1_HMAC,              "CKK_SHA_1_HMAC");
+        addKeyType(CKK_RIPEMD128_HMAC,          "CKK_RIPEMD128_HMAC");
+        addKeyType(CKK_RIPEMD160_HMAC,          "CKK_RIPEMD160_HMAC");
+        addKeyType(CKK_SHA256_HMAC,             "CKK_SHA256_HMAC");
+        addKeyType(CKK_SHA384_HMAC,             "CKK_SHA384_HMAC");
+        addKeyType(CKK_SHA512_HMAC,             "CKK_SHA512_HMAC");
+        addKeyType(CKK_SHA224_HMAC,             "CKK_SHA224_HMAC");
+        addKeyType(CKK_SEED,                    "CKK_SEED");
+        addKeyType(CKK_GOSTR3410,               "CKK_GOSTR3410");
+        addKeyType(CKK_GOSTR3411,               "CKK_GOSTR3411");
+        addKeyType(CKK_GOST28147,               "CKK_GOST28147");
+
         addKeyType(CKK_VENDOR_DEFINED,          "CKK_VENDOR_DEFINED");
 
         addKeyType(PCKK_ANY,                    "*");
@@ -855,6 +1050,16 @@
         addAttribute(CKA_OWNER,                 "CKA_OWNER");
         addAttribute(CKA_ATTR_TYPES,            "CKA_ATTR_TYPES");
         addAttribute(CKA_TRUSTED,               "CKA_TRUSTED");
+        addAttribute(CKA_CERTIFICATE_CATEGORY,  "CKA_CERTIFICATE_CATEGORY");
+        addAttribute(CKA_JAVA_MIDP_SECURITY_DOMAIN,
+                                                "CKA_JAVA_MIDP_SECURITY_DOMAIN");
+        addAttribute(CKA_URL,                   "CKA_URL");
+        addAttribute(CKA_HASH_OF_SUBJECT_PUBLIC_KEY,
+                                                "CKA_HASH_OF_SUBJECT_PUBLIC_KEY");
+        addAttribute(CKA_HASH_OF_ISSUER_PUBLIC_KEY,
+                                                "CKA_HASH_OF_ISSUER_PUBLIC_KEY");
+        addAttribute(CKA_NAME_HASH_ALGORITHM,   "CKA_NAME_HASH_ALGORITHM");
+        addAttribute(CKA_CHECK_VALUE,           "CKA_CHECK_VALUE");
         addAttribute(CKA_KEY_TYPE,              "CKA_KEY_TYPE");
         addAttribute(CKA_SUBJECT,               "CKA_SUBJECT");
         addAttribute(CKA_ID,                    "CKA_ID");
@@ -879,6 +1084,7 @@
         addAttribute(CKA_EXPONENT_1,            "CKA_EXPONENT_1");
         addAttribute(CKA_EXPONENT_2,            "CKA_EXPONENT_2");
         addAttribute(CKA_COEFFICIENT,           "CKA_COEFFICIENT");
+        addAttribute(CKA_PUBLIC_KEY_INFO,       "CKA_PUBLIC_KEY_INFO");
         addAttribute(CKA_PRIME,                 "CKA_PRIME");
         addAttribute(CKA_SUBPRIME,              "CKA_SUBPRIME");
         addAttribute(CKA_BASE,                  "CKA_BASE");
@@ -886,19 +1092,69 @@
         addAttribute(CKA_SUB_PRIME_BITS,        "CKA_SUB_PRIME_BITS");
         addAttribute(CKA_VALUE_BITS,            "CKA_VALUE_BITS");
         addAttribute(CKA_VALUE_LEN,             "CKA_VALUE_LEN");
+
         addAttribute(CKA_EXTRACTABLE,           "CKA_EXTRACTABLE");
         addAttribute(CKA_LOCAL,                 "CKA_LOCAL");
         addAttribute(CKA_NEVER_EXTRACTABLE,     "CKA_NEVER_EXTRACTABLE");
         addAttribute(CKA_ALWAYS_SENSITIVE,      "CKA_ALWAYS_SENSITIVE");
+
         addAttribute(CKA_KEY_GEN_MECHANISM,     "CKA_KEY_GEN_MECHANISM");
         addAttribute(CKA_MODIFIABLE,            "CKA_MODIFIABLE");
+        addAttribute(CKA_COPYABLE,              "CKA_COPYABLE");
+        addAttribute(CKA_DESTROYABLE,           "CKA_DESTROYABLE");
+
         addAttribute(CKA_EC_PARAMS,             "CKA_EC_PARAMS");
         addAttribute(CKA_EC_POINT,              "CKA_EC_POINT");
+
         addAttribute(CKA_SECONDARY_AUTH,        "CKA_SECONDARY_AUTH");
         addAttribute(CKA_AUTH_PIN_FLAGS,        "CKA_AUTH_PIN_FLAGS");
+        addAttribute(CKA_ALWAYS_AUTHENTICATE,   "CKA_ALWAYS_AUTHENTICATE");
+        addAttribute(CKA_WRAP_WITH_TRUSTED,     "CKA_WRAP_WITH_TRUSTED");
+        addAttribute(CKA_WRAP_TEMPLATE,         "CKA_WRAP_TEMPLATE");
+        addAttribute(CKA_UNWRAP_TEMPLATE,       "CKA_UNWRAP_TEMPLATE");
+        addAttribute(CKA_DERIVE_TEMPLATE,       "CKA_DERIVE_TEMPLATE");
+        addAttribute(CKA_OTP_FORMAT,            "CKA_OTP_FORMAT");
+        addAttribute(CKA_OTP_LENGTH,            "CKA_OTP_LENGTH");
+        addAttribute(CKA_OTP_TIME_INTERVAL,     "CKA_OTP_TIME_INTERVAL");
+        addAttribute(CKA_OTP_USER_FRIENDLY_MODE,"CKA_OTP_USER_FRIENDLY_MODE");
+        addAttribute(CKA_OTP_CHALLENGE_REQUIREMENT,
+                                                "CKA_OTP_CHALLENGE_REQUIREMENT");
+        addAttribute(CKA_OTP_TIME_REQUIREMENT,  "CKA_OTP_TIME_REQUIREMENT");
+        addAttribute(CKA_OTP_COUNTER_REQUIREMENT,
+                                                "CKA_OTP_COUNTER_REQUIREMENT");
+        addAttribute(CKA_OTP_PIN_REQUIREMENT,   "CKA_OTP_PIN_REQUIREMENT");
+        addAttribute(CKA_OTP_COUNTER,           "CKA_OTP_COUNTER");
+        addAttribute(CKA_OTP_TIME,              "CKA_OTP_TIME");
+        addAttribute(CKA_OTP_USER_IDENTIFIER,   "CKA_OTP_USER_IDENTIFIER");
+        addAttribute(CKA_OTP_SERVICE_IDENTIFIER,"CKA_OTP_SERVICE_IDENTIFIER");
+        addAttribute(CKA_OTP_SERVICE_LOGO,      "CKA_OTP_SERVICE_LOGO");
+        addAttribute(CKA_OTP_SERVICE_LOGO_TYPE, "CKA_OTP_SERVICE_LOGO_TYPE");
+        addAttribute(CKA_GOSTR3410_PARAMS,      "CKA_GOSTR3410_PARAMS");
+        addAttribute(CKA_GOSTR3411_PARAMS,      "CKA_GOSTR3411_PARAMS");
+        addAttribute(CKA_GOST28147_PARAMS,      "CKA_GOST28147_PARAMS");
+
         addAttribute(CKA_HW_FEATURE_TYPE,       "CKA_HW_FEATURE_TYPE");
         addAttribute(CKA_RESET_ON_INIT,         "CKA_RESET_ON_INIT");
         addAttribute(CKA_HAS_RESET,             "CKA_HAS_RESET");
+
+        addAttribute(CKA_PIXEL_X,               "CKA_PIXEL_X");
+        addAttribute(CKA_PIXEL_Y,               "CKA_PIXEL_Y");
+        addAttribute(CKA_RESOLUTION,            "CKA_RESOLUTION");
+        addAttribute(CKA_CHAR_ROWS,             "CKA_CHAR_ROWS");
+        addAttribute(CKA_CHAR_COLUMNS,          "CKA_CHAR_COLUMNS");
+        addAttribute(CKA_COLOR,                 "CKA_COLOR");
+        addAttribute(CKA_BITS_PER_PIXEL,        "CKA_BITS_PER_PIXEL");
+        addAttribute(CKA_CHAR_SETS,             "CKA_CHAR_SETS");
+        addAttribute(CKA_ENCODING_METHODS,      "CKA_ENCODING_METHODS");
+        addAttribute(CKA_MIME_TYPES,            "CKA_MIME_TYPES");
+        addAttribute(CKA_MECHANISM_TYPE,        "CKA_MECHANISM_TYPE");
+        addAttribute(CKA_REQUIRED_CMS_ATTRIBUTES,
+                                                "CKA_REQUIRED_CMS_ATTRIBUTES");
+        addAttribute(CKA_DEFAULT_CMS_ATTRIBUTES,"CKA_DEFAULT_CMS_ATTRIBUTES");
+        addAttribute(CKA_SUPPORTED_CMS_ATTRIBUTES,
+                                                "CKA_SUPPORTED_CMS_ATTRIBUTES");
+        addAttribute(CKA_ALLOWED_MECHANISMS,    "CKA_ALLOWED_MECHANISMS");
+
         addAttribute(CKA_VENDOR_DEFINED,        "CKA_VENDOR_DEFINED");
         addAttribute(CKA_NETSCAPE_DB,           "CKA_NETSCAPE_DB");
 
@@ -920,6 +1176,11 @@
 
         addObjectClass(PCKO_ANY,                "*");
 
+        addMGF(CKG_MGF1_SHA1,                   "CKG_MGF1_SHA1");
+        addMGF(CKG_MGF1_SHA256,                 "CKG_MGF1_SHA256");
+        addMGF(CKG_MGF1_SHA384,                 "CKG_MGF1_SHA384");
+        addMGF(CKG_MGF1_SHA512,                 "CKG_MGF1_SHA512");
+        addMGF(CKG_MGF1_SHA224,                 "CKG_MGF1_SHA224");
     }
 
 }
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -97,6 +97,12 @@
         // static initializer, hence this method is empty.
     }
 
+    /* *****************************************************************************
+     * Utility, Resource Clean up
+     ******************************************************************************/
+    // always return 0L
+    public static native long freeMechanism(long hMechanism);
+
     /**
      * The PKCS#11 module to connect to. This is the PKCS#11 driver of the token;
      * e.g. pk2priv.dll.
@@ -729,17 +735,25 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @param pData the data to get encrypted and the data's length
+     * @param directIn the address of the to-be-encrypted data
+     * @param in buffer containing the to-be-encrypted data
+     * @param inOfs buffer offset of the to-be-encrypted data
+     * @param inLen length of the to-be-encrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
-     * @return the encrypted data and the encrypted data's length
+     * @param directOut the address for the encrypted data
+     * @param out buffer for the encrypted data
+     * @param outOfs buffer offset for the encrypted data
+     * @param outLen buffer size for the encrypted data
+     * @return the length of encrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
      *                         CK_ULONG_PTR pulEncryptedDataLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
-     * @preconditions (pData <> null)
-     * @postconditions (result <> null)
+     * @preconditions
+     * @postconditions
      */
-    public native int C_Encrypt(long hSession, byte[] in, int inOfs, int inLen,
-            byte[] out, int outOfs, int outLen) throws PKCS11Exception;
+    public native int C_Encrypt(long hSession, long directIn, byte[] in,
+            int inOfs, int inLen, long directOut, byte[] out, int outOfs,
+            int outLen) throws PKCS11Exception;
 
 
     /**
@@ -749,13 +763,20 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @param pPart the data part to get encrypted and the data part's length
+     * @param directIn the address of the to-be-encrypted data
+     * @param in buffer containing the to-be-encrypted data
+     * @param inOfs buffer offset of the to-be-encrypted data
+     * @param inLen length of the to-be-encrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
-     * @return the encrypted data part and the encrypted data part's length
+     * @param directOut the address for the encrypted data
+     * @param out buffer for the encrypted data
+     * @param outOfs buffer offset for the encrypted data
+     * @param outLen buffer size for the encrypted data
+     * @return the length of encrypted data for this update
      *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
                              CK_ULONG_PTR pulEncryptedPartLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
-     * @preconditions (pPart <> null)
+     * @preconditions
      * @postconditions
      */
     public native int C_EncryptUpdate(long hSession, long directIn, byte[] in,
@@ -770,12 +791,16 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @return the last encrypted data part and the last data part's length
+     * @param directOut the address for the encrypted data
+     * @param out buffer for the encrypted data
+     * @param outOfs buffer offset for the encrypted data
+     * @param outLen buffer size for the encrypted data
+     * @return the length of the last part of the encrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pLastEncryptedPart,
                              CK_ULONG_PTR pulLastEncryptedPartLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
      * @preconditions
-     * @postconditions (result <> null)
+     * @postconditions
      */
     public native int C_EncryptFinal(long hSession, long directOut, byte[] out,
             int outOfs, int outLen) throws PKCS11Exception;
@@ -805,18 +830,25 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @param pEncryptedData the encrypted data to get decrypted and the
-     *         encrypted data's length
-     *         (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
-     *                         CK_ULONG ulEncryptedDataLen)
-     * @return the decrypted data and the data's length
+     * @param directIn the address of the to-be-decrypted data
+     * @param in buffer containing the to-be-decrypted data
+     * @param inOfs buffer offset of the to-be-decrypted data
+     * @param inLen length of the to-be-decrypted data
+     *         (PKCS#11 param: CK_BYTE_PTR pDecryptedData,
+     *                         CK_ULONG ulDecryptedDataLen)
+     * @param directOut the address for the decrypted data
+     * @param out buffer for the decrypted data
+     * @param outOfs buffer offset for the decrypted data
+     * @param outLen buffer size for the decrypted data
+     * @return the length of decrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
-     * @preconditions (pEncryptedPart <> null)
-     * @postconditions (result <> null)
+     * @preconditions
+     * @postconditions
      */
-    public native int C_Decrypt(long hSession, byte[] in, int inOfs, int inLen,
-            byte[] out, int outOfs, int outLen) throws PKCS11Exception;
+    public native int C_Decrypt(long hSession, long directIn, byte[] in,
+            int inOfs, int inLen, long directOut, byte[] out, int outOfs,
+            int outLen) throws PKCS11Exception;
 
 
     /**
@@ -826,14 +858,20 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @param pEncryptedPart the encrypted data part to get decrypted and the
-     *         encrypted data part's length
-     *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
-     *                         CK_ULONG ulEncryptedPartLen)
-     * @return the decrypted data part and the data part's length
+     * @param directIn the address of the to-be-decrypted data
+     * @param in buffer containing the to-be-decrypted data
+     * @param inOfs buffer offset of the to-be-decrypted data
+     * @param inLen length of the to-be-decrypted data
+     *         (PKCS#11 param: CK_BYTE_PTR pDecryptedPart,
+     *                         CK_ULONG ulDecryptedPartLen)
+     * @param directOut the address for the decrypted data
+     * @param out buffer for the decrypted data
+     * @param outOfs buffer offset for the decrypted data
+     * @param outLen buffer size for the decrypted data
+     * @return the length of decrypted data for this update
      *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
-     * @preconditions (pEncryptedPart <> null)
+     * @preconditions
      * @postconditions
      */
     public native int C_DecryptUpdate(long hSession, long directIn, byte[] in,
@@ -848,12 +886,16 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
-     * @return the last decrypted data part and the last data part's length
+     * @param directOut the address for the decrypted data
+     * @param out buffer for the decrypted data
+     * @param outOfs buffer offset for the decrypted data
+     * @param outLen buffer size for the decrypted data
+     * @return the length of this last part of decrypted data
      *         (PKCS#11 param: CK_BYTE_PTR pLastPart,
      *                         CK_ULONG_PTR pulLastPartLen)
      * @exception PKCS11Exception If function returns other value than CKR_OK.
      * @preconditions
-     * @postconditions (result <> null)
+     * @postconditions
      */
     public native int C_DecryptFinal(long hSession, long directOut, byte[] out,
             int outOfs, int outLen) throws PKCS11Exception;
@@ -1027,6 +1069,7 @@
      *
      * @param hSession the session's handle
      *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
+     * @param expectedLen expected signature length, can be 0 if unknown
      * @return the signature and the signature's length
      *         (PKCS#11 param: CK_BYTE_PTR pSignature,
      *                         CK_ULONG_PTR pulSignatureLen)
@@ -1285,7 +1328,6 @@
 //            byte[] pEncryptedPart) throws PKCS11Exception;
 
 
-
 /* *****************************************************************************
  * Key management
  ******************************************************************************/
@@ -1692,10 +1734,11 @@
         super.C_EncryptInit(hSession, pMechanism, hKey);
     }
 
-    public synchronized int C_Encrypt(long hSession, byte[] in, int inOfs,
-            int inLen, byte[] out, int outOfs, int outLen)
+    public synchronized int C_Encrypt(long hSession, long directIn, byte[] in,
+            int inOfs, int inLen, long directOut, byte[] out, int outOfs, int outLen)
             throws PKCS11Exception {
-        return super.C_Encrypt(hSession, in, inOfs, inLen, out, outOfs, outLen);
+        return super.C_Encrypt(hSession, directIn, in, inOfs, inLen,
+                directOut, out, outOfs, outLen);
     }
 
     public synchronized int C_EncryptUpdate(long hSession, long directIn,
@@ -1715,10 +1758,11 @@
         super.C_DecryptInit(hSession, pMechanism, hKey);
     }
 
-    public synchronized int C_Decrypt(long hSession, byte[] in, int inOfs,
-            int inLen, byte[] out, int outOfs, int outLen)
-            throws PKCS11Exception {
-        return super.C_Decrypt(hSession, in, inOfs, inLen, out, outOfs, outLen);
+    public synchronized int C_Decrypt(long hSession, long directIn,
+            byte[] in, int inOfs, int inLen, long directOut, byte[] out,
+            int outOfs, int outLen) throws PKCS11Exception {
+        return super.C_Decrypt(hSession, directIn, in, inOfs, inLen,
+                directOut, out, outOfs, outLen);
     }
 
     public synchronized int C_DecryptUpdate(long hSession, long directIn,
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -144,98 +144,46 @@
     /* normal user's PIN is set */
     public static final long  CKF_USER_PIN_INITIALIZED    = 0x00000008L;
 
-    /* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0.  If it is set,
-     * that means that *every* time the state of cryptographic
-     * operations of a session is successfully saved, all keys
-     * needed to continue those operations are stored in the state */
     public static final long  CKF_RESTORE_KEY_NOT_NEEDED  = 0x00000020L;
 
-    /* CKF_CLOCK_ON_TOKEN is new for v2.0.  If it is set, that means
-     * that the token has some sort of clock.  The time on that
-     * clock is returned in the token info structure */
     public static final long  CKF_CLOCK_ON_TOKEN          = 0x00000040L;
 
-    /* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0.  If it is
-     * set, that means that there is some way for the user to login
-     * without sending a PIN through the Cryptoki library itself */
     public static final long  CKF_PROTECTED_AUTHENTICATION_PATH = 0x00000100L;
 
-    /* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0.  If it is true,
-     * that means that a single session with the token can perform
-     * dual simultaneous cryptographic operations (digest and
-     * encrypt; decrypt and digest; sign and encrypt; and decrypt
-     * and sign) */
     public static final long  CKF_DUAL_CRYPTO_OPERATIONS  = 0x00000200L;
 
-    /* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the
-     * token has been initialized using C_InitializeToken or an
-     * equivalent mechanism outside the scope of PKCS #11.
-     * Calling C_InitializeToken when this flag is set will cause
-     * the token to be reinitialized. */
     public static final long  CKF_TOKEN_INITIALIZED       = 0x00000400L;
 
-    /* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is
-     * true, the token supports secondary authentication for
-     * private key objects. */
     public static final long  CKF_SECONDARY_AUTHENTICATION  = 0x00000800L;
 
-    /* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an
-     * incorrect user login PIN has been entered at least once
-     * since the last successful authentication. */
     public static final long  CKF_USER_PIN_COUNT_LOW       = 0x00010000L;
 
-    /* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true,
-     * supplying an incorrect user PIN will it to become locked. */
     public static final long  CKF_USER_PIN_FINAL_TRY       = 0x00020000L;
 
-    /* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the
-     * user PIN has been locked. User login to the token is not
-     * possible. */
     public static final long  CKF_USER_PIN_LOCKED          = 0x00040000L;
 
-    /* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
-     * the user PIN value is the default value set by token
-     * initialization or manufacturing. */
     public static final long  CKF_USER_PIN_TO_BE_CHANGED   = 0x00080000L;
 
-    /* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an
-     * incorrect SO login PIN has been entered at least once since
-     * the last successful authentication. */
     public static final long  CKF_SO_PIN_COUNT_LOW         = 0x00100000L;
 
-    /* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true,
-     * supplying an incorrect SO PIN will it to become locked. */
     public static final long  CKF_SO_PIN_FINAL_TRY         = 0x00200000L;
 
-    /* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO
-     * PIN has been locked. SO login to the token is not possible.
-     */
     public static final long  CKF_SO_PIN_LOCKED            = 0x00400000L;
 
-    /* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
-     * the SO PIN value is the default value set by token
-     * initialization or manufacturing. */
     public static final long  CKF_SO_PIN_TO_BE_CHANGED     = 0x00800000L;
 
-
-    /* CK_USER_TYPE enumerates the types of Cryptoki users */
-    /* CK_USER_TYPE has been changed from an enum to a CK_ULONG for
-     * v2.0 */
     /* Security Officer */
     public static final long CKU_SO = 0L;
     /* Normal user */
     public static final long CKU_USER = 1L;
 
     /* CK_STATE enumerates the session states */
-    /* CK_STATE has been changed from an enum to a CK_ULONG for
-     * v2.0 */
     public static final long  CKS_RO_PUBLIC_SESSION = 0L;
     public static final long  CKS_RO_USER_FUNCTIONS = 1L;
     public static final long  CKS_RW_PUBLIC_SESSION = 2L;
     public static final long  CKS_RW_USER_FUNCTIONS = 3L;
     public static final long  CKS_RW_SO_FUNCTIONS   = 4L;
 
-
     /* The flags are defined in the following table:
      *      Bit Flag                Mask        Meaning
      */
@@ -246,8 +194,6 @@
 
 
     /* The following classes of objects are defined: */
-    /* CKO_HW_FEATURE is new for v2.10 */
-    /* CKO_DOMAIN_PARAMETERS is new for v2.11 */
     public static final long  CKO_DATA              = 0x00000000L;
     public static final long  CKO_CERTIFICATE       = 0x00000001L;
     public static final long  CKO_PUBLIC_KEY        = 0x00000002L;
@@ -267,62 +213,73 @@
     public static final long  CKH_VENDOR_DEFINED    = 0x80000000L;
 
     /* the following key types are defined: */
-    public static final long  CKK_RSA             = 0x00000000L;
-    public static final long  CKK_DSA             = 0x00000001L;
-    public static final long  CKK_DH              = 0x00000002L;
-
-    /* CKK_ECDSA and CKK_KEA are new for v2.0 */
-    /* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */
-    public static final long  CKK_ECDSA           = 0x00000003L;
-    public static final long  CKK_EC              = 0x00000003L;
-    public static final long  CKK_X9_42_DH        = 0x00000004L;
-    public static final long  CKK_KEA             = 0x00000005L;
-
-    public static final long  CKK_GENERIC_SECRET  = 0x00000010L;
-    public static final long  CKK_RC2             = 0x00000011L;
-    public static final long  CKK_RC4             = 0x00000012L;
-    public static final long  CKK_DES             = 0x00000013L;
-    public static final long  CKK_DES2            = 0x00000014L;
-    public static final long  CKK_DES3            = 0x00000015L;
+    public static final long  CKK_RSA                  = 0x00000000L;
+    public static final long  CKK_DSA                  = 0x00000001L;
+    public static final long  CKK_DH                   = 0x00000002L;
+    public static final long  CKK_ECDSA /*deprecated*/ = 0x00000003L;
+    public static final long  CKK_EC                   = 0x00000003L;
+    public static final long  CKK_X9_42_DH             = 0x00000004L;
+    public static final long  CKK_KEA                  = 0x00000005L;
+    public static final long  CKK_GENERIC_SECRET       = 0x00000010L;
+    public static final long  CKK_RC2                  = 0x00000011L;
+    public static final long  CKK_RC4                  = 0x00000012L;
+    public static final long  CKK_DES                  = 0x00000013L;
+    public static final long  CKK_DES2                 = 0x00000014L;
+    public static final long  CKK_DES3                 = 0x00000015L;
 
-    /* all these key types are new for v2.0 */
-    public static final long  CKK_CAST            = 0x00000016L;
-    public static final long  CKK_CAST3           = 0x00000017L;
-    /* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */
-    public static final long  CKK_CAST5           = 0x00000018L;
-    /* CAST128=CAST5 */
-    public static final long  CKK_CAST128         = 0x00000018L;
-    public static final long  CKK_RC5             = 0x00000019L;
-    public static final long  CKK_IDEA            = 0x0000001AL;
-    public static final long  CKK_SKIPJACK        = 0x0000001BL;
-    public static final long  CKK_BATON           = 0x0000001CL;
-    public static final long  CKK_JUNIPER         = 0x0000001DL;
-    public static final long  CKK_CDMF            = 0x0000001EL;
-    public static final long  CKK_AES             = 0x0000001FL;
-    // v2.20
-    public static final long  CKK_BLOWFISH        = 0x00000020L;
+    public static final long  CKK_CAST                 = 0x00000016L;
+    public static final long  CKK_CAST3                = 0x00000017L;
+    public static final long  CKK_CAST5 /*deprecated*/ = 0x00000018L;
+    public static final long  CKK_CAST128              = 0x00000018L;
+    public static final long  CKK_RC5                  = 0x00000019L;
+    public static final long  CKK_IDEA                 = 0x0000001AL;
+    public static final long  CKK_SKIPJACK             = 0x0000001BL;
+    public static final long  CKK_BATON                = 0x0000001CL;
+    public static final long  CKK_JUNIPER              = 0x0000001DL;
+    public static final long  CKK_CDMF                 = 0x0000001EL;
+    public static final long  CKK_AES                  = 0x0000001FL;
+    public static final long  CKK_BLOWFISH             = 0x00000020L;
+    public static final long  CKK_TWOFISH              = 0x00000021L;
+    public static final long  CKK_SECURID              = 0x00000022L;
+    public static final long  CKK_HOTP                 = 0x00000023L;
+    public static final long  CKK_ACTI                 = 0x00000024L;
+    public static final long  CKK_CAMELLIA             = 0x00000025L;
+    public static final long  CKK_ARIA                 = 0x00000026L;
 
-    public static final long  CKK_VENDOR_DEFINED  = 0x80000000L;
+    public static final long  CKK_MD5_HMAC             = 0x00000027L;
+    public static final long  CKK_SHA_1_HMAC           = 0x00000028L;
+    public static final long  CKK_RIPEMD128_HMAC       = 0x00000029L;
+    public static final long  CKK_RIPEMD160_HMAC       = 0x0000002AL;
+    public static final long  CKK_SHA256_HMAC          = 0x0000002BL;
+    public static final long  CKK_SHA384_HMAC          = 0x0000002CL;
+    public static final long  CKK_SHA512_HMAC          = 0x0000002DL;
+    public static final long  CKK_SHA224_HMAC          = 0x0000002EL;
 
-    // new for v2.20 amendment 3
-    //public static final long  CKK_CAMELLIA          = 0x00000025L;
-    //public static final long  CKK_ARIA              = 0x00000026L;
+    public static final long  CKK_SEED                 = 0x0000002FL;
+    public static final long  CKK_GOSTR3410            = 0x00000030L;
+    public static final long  CKK_GOSTR3411            = 0x00000031L;
+    public static final long  CKK_GOST28147            = 0x00000032L;
+;
+    public static final long  CKK_VENDOR_DEFINED       = 0x80000000L;
 
     // pseudo key type ANY (for template manager)
-    public static final long  PCKK_ANY            = 0x7FFFFF22L;
+    public static final long  PCKK_ANY                 = 0x7FFFFF22L;
 
-    public static final long  PCKK_HMAC            = 0x7FFFFF23L;
-    public static final long  PCKK_SSLMAC          = 0x7FFFFF24L;
-    public static final long  PCKK_TLSPREMASTER    = 0x7FFFFF25L;
-    public static final long  PCKK_TLSRSAPREMASTER = 0x7FFFFF26L;
-    public static final long  PCKK_TLSMASTER       = 0x7FFFFF27L;
+    public static final long  PCKK_HMAC                = 0x7FFFFF23L;
+    public static final long  PCKK_SSLMAC              = 0x7FFFFF24L;
+    public static final long  PCKK_TLSPREMASTER        = 0x7FFFFF25L;
+    public static final long  PCKK_TLSRSAPREMASTER     = 0x7FFFFF26L;
+    public static final long  PCKK_TLSMASTER           = 0x7FFFFF27L;
 
     /* The following certificate types are defined: */
-    /* CKC_X_509_ATTR_CERT is new for v2.10 */
-    public static final long  CKC_X_509           = 0x00000000L;
-    public static final long  CKC_X_509_ATTR_CERT = 0x00000001L;
-    public static final long  CKC_VENDOR_DEFINED  = 0x80000000L;
+    public static final long  CKC_X_509                = 0x00000000L;
+    public static final long  CKC_X_509_ATTR_CERT      = 0x00000001L;
+    public static final long  CKC_VENDOR_DEFINED       = 0x80000000L;
 
+    /* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which
+     * consists of an array of values.
+     */
+    public static final long  CKF_ARRAY_ATTRIBUTE      = 0x40000000L;
 
     /* The following attribute types are defined: */
     public static final long  CKA_CLASS              = 0x00000000L;
@@ -331,22 +288,26 @@
     public static final long  CKA_LABEL              = 0x00000003L;
     public static final long  CKA_APPLICATION        = 0x00000010L;
     public static final long  CKA_VALUE              = 0x00000011L;
-
-    /* CKA_OBJECT_ID is new for v2.10 */
     public static final long  CKA_OBJECT_ID          = 0x00000012L;
-
     public static final long  CKA_CERTIFICATE_TYPE   = 0x00000080L;
     public static final long  CKA_ISSUER             = 0x00000081L;
     public static final long  CKA_SERIAL_NUMBER      = 0x00000082L;
-
-    /* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new L;
-     * for v2.10 */
     public static final long  CKA_AC_ISSUER          = 0x00000083L;
     public static final long  CKA_OWNER              = 0x00000084L;
     public static final long  CKA_ATTR_TYPES         = 0x00000085L;
-
-    /* CKA_TRUSTED is new for v2.11 */
     public static final long  CKA_TRUSTED            = 0x00000086L;
+    public static final long  CKA_CERTIFICATE_CATEGORY
+                                                     = 0x00000087L;
+    public static final long  CKA_JAVA_MIDP_SECURITY_DOMAIN
+                                                     = 0x00000088L;
+    public static final long  CKA_URL                = 0x00000089L;
+    public static final long  CKA_HASH_OF_SUBJECT_PUBLIC_KEY
+                                                     = 0x0000008AL;
+    public static final long  CKA_HASH_OF_ISSUER_PUBLIC_KEY
+                                                     = 0x0000008BL;
+    public static final long  CKA_NAME_HASH_ALGORITHM
+                                                     = 0x0000008CL;
+    public static final long  CKA_CHECK_VALUE        = 0x00000090L;
 
     public static final long  CKA_KEY_TYPE           = 0x00000100L;
     public static final long  CKA_SUBJECT            = 0x00000101L;
@@ -372,45 +333,79 @@
     public static final long  CKA_EXPONENT_1         = 0x00000126L;
     public static final long  CKA_EXPONENT_2         = 0x00000127L;
     public static final long  CKA_COEFFICIENT        = 0x00000128L;
+    public static final long  CKA_PUBLIC_KEY_INFO    = 0x00000129L;
     public static final long  CKA_PRIME              = 0x00000130L;
     public static final long  CKA_SUBPRIME           = 0x00000131L;
     public static final long  CKA_BASE               = 0x00000132L;
 
-    /* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */
     public static final long  CKA_PRIME_BITS         = 0x00000133L;
     public static final long  CKA_SUB_PRIME_BITS     = 0x00000134L;
 
     public static final long  CKA_VALUE_BITS         = 0x00000160L;
     public static final long  CKA_VALUE_LEN          = 0x00000161L;
 
-    /* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE,
-     * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS,
-     * and CKA_EC_POINT are new for v2.0 */
     public static final long  CKA_EXTRACTABLE        = 0x00000162L;
     public static final long  CKA_LOCAL              = 0x00000163L;
     public static final long  CKA_NEVER_EXTRACTABLE  = 0x00000164L;
     public static final long  CKA_ALWAYS_SENSITIVE   = 0x00000165L;
 
-    /* CKA_KEY_GEN_MECHANISM is new for v2.11 */
     public static final long  CKA_KEY_GEN_MECHANISM  = 0x00000166L;
 
     public static final long  CKA_MODIFIABLE         = 0x00000170L;
+    public static final long  CKA_COPYABLE           = 0x00000171L;
+    public static final long  CKA_DESTROYABLE        = 0x00000172L;
 
-    /* CKA_ECDSA_PARAMS is deprecated in v2.11,
-     * CKA_EC_PARAMS is preferred. */
-    public static final long  CKA_ECDSA_PARAMS       = 0x00000180L;
-    public static final long  CKA_EC_PARAMS          = 0x00000180L;
-    public static final long  CKA_EC_POINT           = 0x00000181L;
+    public static final long  CKA_ECDSA_PARAMS /*deprecated*/  = 0x00000180L;
+    public static final long  CKA_EC_PARAMS                    = 0x00000180L;
+    public static final long  CKA_EC_POINT                     = 0x00000181L;
+
+    public static final long  CKA_SECONDARY_AUTH /*deprecated*/= 0x00000200L;
+    public static final long  CKA_AUTH_PIN_FLAGS /*deprecated*/= 0x00000201L;
+    public static final long  CKA_ALWAYS_AUTHENTICATE          = 0x00000202L;
+    public static final long  CKA_WRAP_WITH_TRUSTED  = 0x00000210L;
+    public static final long  CKA_WRAP_TEMPLATE      = (CKF_ARRAY_ATTRIBUTE|0x00000211L);
+    public static final long  CKA_UNWRAP_TEMPLATE    = (CKF_ARRAY_ATTRIBUTE|0x00000212L);
+    public static final long  CKA_DERIVE_TEMPLATE    = (CKF_ARRAY_ATTRIBUTE|0x00000213L);
 
-    /* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
-     * CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET
-     * are new for v2.10 */
-    public static final long  CKA_SECONDARY_AUTH     = 0x00000200L;
-    public static final long  CKA_AUTH_PIN_FLAGS     = 0x00000201L;
+    public static final long  CKA_OTP_FORMAT         = 0x00000220L;
+    public static final long  CKA_OTP_LENGTH         = 0x00000221L;
+    public static final long  CKA_OTP_TIME_INTERVAL  = 0x00000222L;
+    public static final long  CKA_OTP_USER_FRIENDLY_MODE       = 0x00000223L;
+    public static final long  CKA_OTP_CHALLENGE_REQUIREMENT    = 0x00000224L;
+    public static final long  CKA_OTP_TIME_REQUIREMENT         = 0x00000225L;
+    public static final long  CKA_OTP_COUNTER_REQUIREMENT      = 0x00000226L;
+    public static final long  CKA_OTP_PIN_REQUIREMENT          = 0x00000227L;
+    public static final long  CKA_OTP_COUNTER        = 0x0000022EL;
+    public static final long  CKA_OTP_TIME           = 0x0000022FL;
+    public static final long  CKA_OTP_USER_IDENTIFIER          = 0x0000022AL;
+    public static final long  CKA_OTP_SERVICE_IDENTIFIER       = 0x0000022BL;
+    public static final long  CKA_OTP_SERVICE_LOGO   = 0x0000022CL;
+    public static final long  CKA_OTP_SERVICE_LOGO_TYPE        = 0x0000022DL;
+
+    public static final long  CKA_GOSTR3410_PARAMS   = 0x00000250L;
+    public static final long  CKA_GOSTR3411_PARAMS   = 0x00000251L;
+    public static final long  CKA_GOST28147_PARAMS   = 0x00000252L;
+
     public static final long  CKA_HW_FEATURE_TYPE    = 0x00000300L;
     public static final long  CKA_RESET_ON_INIT      = 0x00000301L;
     public static final long  CKA_HAS_RESET          = 0x00000302L;
 
+    public static final long  CKA_PIXEL_X            = 0x00000400L;
+    public static final long  CKA_PIXEL_Y            = 0x00000401L;
+    public static final long  CKA_RESOLUTION         = 0x00000402L;
+    public static final long  CKA_CHAR_ROWS          = 0x00000403L;
+    public static final long  CKA_CHAR_COLUMNS       = 0x00000404L;
+    public static final long  CKA_COLOR              = 0x00000405L;
+    public static final long  CKA_BITS_PER_PIXEL     = 0x00000406L;
+    public static final long  CKA_CHAR_SETS          = 0x00000480L;
+    public static final long  CKA_ENCODING_METHODS   = 0x00000481L;
+    public static final long  CKA_MIME_TYPES         = 0x00000482L;
+    public static final long  CKA_MECHANISM_TYPE     = 0x00000500L;
+    public static final long  CKA_REQUIRED_CMS_ATTRIBUTES      = 0x00000501L;
+    public static final long  CKA_DEFAULT_CMS_ATTRIBUTES       = 0x00000502L;
+    public static final long  CKA_SUPPORTED_CMS_ATTRIBUTES     = 0x00000503L;
+    public static final long  CKA_ALLOWED_MECHANISMS = (CKF_ARRAY_ATTRIBUTE|0x00000600L);
+
     public static final long  CKA_VENDOR_DEFINED     = 0x80000000L;
 
     /* the following mechanism types are defined: */
@@ -419,20 +414,14 @@
     public static final long  CKM_RSA_9796                   = 0x00000002L;
     public static final long  CKM_RSA_X_509                  = 0x00000003L;
 
-    /* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS
-     * are new for v2.0.  They are mechanisms which hash and sign */
     public static final long  CKM_MD2_RSA_PKCS               = 0x00000004L;
     public static final long  CKM_MD5_RSA_PKCS               = 0x00000005L;
     public static final long  CKM_SHA1_RSA_PKCS              = 0x00000006L;
 
-    /* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and
-     * CKM_RSA_PKCS_OAEP are new for v2.10 */
     public static final long  CKM_RIPEMD128_RSA_PKCS         = 0x00000007L;
     public static final long  CKM_RIPEMD160_RSA_PKCS         = 0x00000008L;
     public static final long  CKM_RSA_PKCS_OAEP              = 0x00000009L;
 
-    /* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31,
-     * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */
     public static final long  CKM_RSA_X9_31_KEY_PAIR_GEN     = 0x0000000AL;
     public static final long  CKM_RSA_X9_31                  = 0x0000000BL;
     public static final long  CKM_SHA1_RSA_X9_31             = 0x0000000CL;
@@ -442,28 +431,48 @@
     public static final long  CKM_DSA_KEY_PAIR_GEN           = 0x00000010L;
     public static final long  CKM_DSA                        = 0x00000011L;
     public static final long  CKM_DSA_SHA1                   = 0x00000012L;
+    public static final long  CKM_DSA_SHA224                 = 0x00000013L;
+    public static final long  CKM_DSA_SHA256                 = 0x00000014L;
+    public static final long  CKM_DSA_SHA384                 = 0x00000015L;
+    public static final long  CKM_DSA_SHA512                 = 0x00000016L;
+
     public static final long  CKM_DH_PKCS_KEY_PAIR_GEN       = 0x00000020L;
     public static final long  CKM_DH_PKCS_DERIVE             = 0x00000021L;
 
-    /* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE,
-     * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for
-     * v2.11 */
     public static final long  CKM_X9_42_DH_KEY_PAIR_GEN      = 0x00000030L;
     public static final long  CKM_X9_42_DH_DERIVE            = 0x00000031L;
     public static final long  CKM_X9_42_DH_HYBRID_DERIVE     = 0x00000032L;
     public static final long  CKM_X9_42_MQV_DERIVE           = 0x00000033L;
 
-    // v2.20
     public static final long  CKM_SHA256_RSA_PKCS            = 0x00000040L;
     public static final long  CKM_SHA384_RSA_PKCS            = 0x00000041L;
     public static final long  CKM_SHA512_RSA_PKCS            = 0x00000042L;
+    public static final long  CKM_SHA256_RSA_PKCS_PSS        = 0x00000043L;
+    public static final long  CKM_SHA384_RSA_PKCS_PSS        = 0x00000044L;
+    public static final long  CKM_SHA512_RSA_PKCS_PSS        = 0x00000045L;
+
+    public static final long  CKM_SHA224_RSA_PKCS            = 0x00000046L;
+    public static final long  CKM_SHA224_RSA_PKCS_PSS        = 0x00000047L;
+
+    public static final long  CKM_SHA512_224                 = 0x00000048L;
+    public static final long  CKM_SHA512_224_HMAC            = 0x00000049L;
+    public static final long  CKM_SHA512_224_HMAC_GENERAL    = 0x0000004AL;
+    public static final long  CKM_SHA512_224_KEY_DERIVATION  = 0x0000004BL;
+    public static final long  CKM_SHA512_256                 = 0x0000004CL;
+    public static final long  CKM_SHA512_256_HMAC            = 0x0000004DL;
+    public static final long  CKM_SHA512_256_HMAC_GENERAL    = 0x0000004EL;
+    public static final long  CKM_SHA512_256_KEY_DERIVATION  = 0x0000004FL;
+
+    public static final long  CKM_SHA512_T                   = 0x00000050L;
+    public static final long  CKM_SHA512_T_HMAC              = 0x00000051L;
+    public static final long  CKM_SHA512_T_HMAC_GENERAL      = 0x00000052L;
+    public static final long  CKM_SHA512_T_KEY_DERIVATION    = 0x00000053L;
 
     public static final long  CKM_RC2_KEY_GEN                = 0x00000100L;
     public static final long  CKM_RC2_ECB                    = 0x00000101L;
     public static final long  CKM_RC2_CBC                    = 0x00000102L;
     public static final long  CKM_RC2_MAC                    = 0x00000103L;
 
-    /* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */
     public static final long  CKM_RC2_MAC_GENERAL            = 0x00000104L;
     public static final long  CKM_RC2_CBC_PAD                = 0x00000105L;
 
@@ -474,7 +483,6 @@
     public static final long  CKM_DES_CBC                    = 0x00000122L;
     public static final long  CKM_DES_MAC                    = 0x00000123L;
 
-    /* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */
     public static final long  CKM_DES_MAC_GENERAL            = 0x00000124L;
     public static final long  CKM_DES_CBC_PAD                = 0x00000125L;
 
@@ -484,11 +492,10 @@
     public static final long  CKM_DES3_CBC                   = 0x00000133L;
     public static final long  CKM_DES3_MAC                   = 0x00000134L;
 
-    /* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,
-     * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,
-     * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */
     public static final long  CKM_DES3_MAC_GENERAL           = 0x00000135L;
     public static final long  CKM_DES3_CBC_PAD               = 0x00000136L;
+    public static final long  CKM_DES3_CMAC_GENERAL          = 0x00000137L;
+    public static final long  CKM_DES3_CMAC                  = 0x00000138L;
     public static final long  CKM_CDMF_KEY_GEN               = 0x00000140L;
     public static final long  CKM_CDMF_ECB                   = 0x00000141L;
     public static final long  CKM_CDMF_CBC                   = 0x00000142L;
@@ -496,27 +503,26 @@
     public static final long  CKM_CDMF_MAC_GENERAL           = 0x00000144L;
     public static final long  CKM_CDMF_CBC_PAD               = 0x00000145L;
 
+    public static final long  CKM_DES_OFB64                  = 0x00000150L;
+    public static final long  CKM_DES_OFB8                   = 0x00000151L;
+    public static final long  CKM_DES_CFB64                  = 0x00000152L;
+    public static final long  CKM_DES_CFB8                   = 0x00000153L;
+
     public static final long  CKM_MD2                        = 0x00000200L;
 
-    /* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */
     public static final long  CKM_MD2_HMAC                   = 0x00000201L;
     public static final long  CKM_MD2_HMAC_GENERAL           = 0x00000202L;
 
     public static final long  CKM_MD5                        = 0x00000210L;
 
-    /* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */
     public static final long  CKM_MD5_HMAC                   = 0x00000211L;
     public static final long  CKM_MD5_HMAC_GENERAL           = 0x00000212L;
 
     public static final long  CKM_SHA_1                      = 0x00000220L;
 
-    /* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */
     public static final long  CKM_SHA_1_HMAC                 = 0x00000221L;
     public static final long  CKM_SHA_1_HMAC_GENERAL         = 0x00000222L;
 
-    /* CKM_RIPEMD128, CKM_RIPEMD128_HMAC,
-     * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,
-     * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */
     public static final long  CKM_RIPEMD128                  = 0x00000230L;
     public static final long  CKM_RIPEMD128_HMAC             = 0x00000231L;
     public static final long  CKM_RIPEMD128_HMAC_GENERAL     = 0x00000232L;
@@ -524,11 +530,12 @@
     public static final long  CKM_RIPEMD160_HMAC             = 0x00000241L;
     public static final long  CKM_RIPEMD160_HMAC_GENERAL     = 0x00000242L;
 
-    // v2.20
     public static final long  CKM_SHA256                     = 0x00000250L;
     public static final long  CKM_SHA256_HMAC                = 0x00000251L;
     public static final long  CKM_SHA256_HMAC_GENERAL        = 0x00000252L;
-
+    public static final long  CKM_SHA224                     = 0x00000255L;
+    public static final long  CKM_SHA224_HMAC                = 0x00000256L;
+    public static final long  CKM_SHA224_HMAC_GENERAL        = 0x00000257L;
     public static final long  CKM_SHA384                     = 0x00000260L;
     public static final long  CKM_SHA384_HMAC                = 0x00000261L;
     public static final long  CKM_SHA384_HMAC_GENERAL        = 0x00000262L;
@@ -537,8 +544,13 @@
     public static final long  CKM_SHA512_HMAC                = 0x00000271L;
     public static final long  CKM_SHA512_HMAC_GENERAL        = 0x00000272L;
 
-    /* All of the following mechanisms are new for v2.0 */
-    /* Note that CAST128 and CAST5 are the same algorithm */
+    public static final long  CKM_SECURID_KEY_GEN            = 0x00000280L;
+    public static final long  CKM_SECURID                    = 0x00000282L;
+    public static final long  CKM_HOTP_KEY_GEN               = 0x00000290L;
+    public static final long  CKM_HOTP                       = 0x00000291L;
+    public static final long  CKM_ACTI                       = 0x000002A0L;
+    public static final long  CKM_ACTI_KEY_GEN               = 0x000002A1L;
+
     public static final long  CKM_CAST_KEY_GEN               = 0x00000300L;
     public static final long  CKM_CAST_ECB                   = 0x00000301L;
     public static final long  CKM_CAST_CBC                   = 0x00000302L;
@@ -551,18 +563,20 @@
     public static final long  CKM_CAST3_MAC                  = 0x00000313L;
     public static final long  CKM_CAST3_MAC_GENERAL          = 0x00000314L;
     public static final long  CKM_CAST3_CBC_PAD              = 0x00000315L;
-    public static final long  CKM_CAST5_KEY_GEN              = 0x00000320L;
-    public static final long  CKM_CAST128_KEY_GEN            = 0x00000320L;
-    public static final long  CKM_CAST5_ECB                  = 0x00000321L;
-    public static final long  CKM_CAST128_ECB                = 0x00000321L;
-    public static final long  CKM_CAST5_CBC                  = 0x00000322L;
-    public static final long  CKM_CAST128_CBC                = 0x00000322L;
-    public static final long  CKM_CAST5_MAC                  = 0x00000323L;
-    public static final long  CKM_CAST128_MAC                = 0x00000323L;
-    public static final long  CKM_CAST5_MAC_GENERAL          = 0x00000324L;
-    public static final long  CKM_CAST128_MAC_GENERAL        = 0x00000324L;
-    public static final long  CKM_CAST5_CBC_PAD              = 0x00000325L;
-    public static final long  CKM_CAST128_CBC_PAD            = 0x00000325L;
+    /* Note that CAST128 and CAST5 are the same algorithm */
+    public static final long  CKM_CAST5_KEY_GEN                = 0x00000320L;
+    public static final long  CKM_CAST128_KEY_GEN              = 0x00000320L;
+    public static final long  CKM_CAST5_ECB                    = 0x00000321L;
+    public static final long  CKM_CAST128_ECB                  = 0x00000321L;
+    public static final long  CKM_CAST5_CBC /*deprecated*/     = 0x00000322L;
+    public static final long  CKM_CAST128_CBC                  = 0x00000322L;
+    public static final long  CKM_CAST5_MAC /*deprecated*/     = 0x00000323L;
+    public static final long  CKM_CAST128_MAC                  = 0x00000323L;
+    public static final long  CKM_CAST5_MAC_GENERAL /*deprecated*/
+                                                               = 0x00000324L;
+    public static final long  CKM_CAST128_MAC_GENERAL          = 0x00000324L;
+    public static final long  CKM_CAST5_CBC_PAD /*deprecated*/ = 0x00000325L;
+    public static final long  CKM_CAST128_CBC_PAD              = 0x00000325L;
     public static final long  CKM_RC5_KEY_GEN                = 0x00000330L;
     public static final long  CKM_RC5_ECB                    = 0x00000331L;
     public static final long  CKM_RC5_CBC                    = 0x00000332L;
@@ -585,9 +599,6 @@
     public static final long  CKM_SSL3_MASTER_KEY_DERIVE     = 0x00000371L;
     public static final long  CKM_SSL3_KEY_AND_MAC_DERIVE    = 0x00000372L;
 
-    /* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,
-     * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and
-     * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */
     public static final long  CKM_SSL3_MASTER_KEY_DERIVE_DH  = 0x00000373L;
     public static final long  CKM_TLS_PRE_MASTER_KEY_GEN     = 0x00000374L;
     public static final long  CKM_TLS_MASTER_KEY_DERIVE      = 0x00000375L;
@@ -601,10 +612,10 @@
     public static final long  CKM_MD2_KEY_DERIVATION         = 0x00000391L;
     public static final long  CKM_SHA1_KEY_DERIVATION        = 0x00000392L;
 
-    // v2.20
     public static final long  CKM_SHA256_KEY_DERIVATION      = 0x00000393L;
     public static final long  CKM_SHA384_KEY_DERIVATION      = 0x00000394L;
     public static final long  CKM_SHA512_KEY_DERIVATION      = 0x00000395L;
+    public static final long  CKM_SHA224_KEY_DERIVATION      = 0x00000396L;
 
     public static final long  CKM_PBE_MD2_DES_CBC            = 0x000003A0L;
     public static final long  CKM_PBE_MD5_DES_CBC            = 0x000003A1L;
@@ -621,22 +632,65 @@
     public static final long  CKM_PBE_SHA1_RC2_128_CBC       = 0x000003AAL;
     public static final long  CKM_PBE_SHA1_RC2_40_CBC        = 0x000003ABL;
 
-    /* CKM_PKCS5_PBKD2 is new for v2.10 */
     public static final long  CKM_PKCS5_PBKD2                = 0x000003B0L;
 
     public static final long  CKM_PBA_SHA1_WITH_SHA1_HMAC    = 0x000003C0L;
 
-    /* CKM_TLS12_MASTER_KEY_DERIVE, CKM_TLS12_KEY_AND_MAC_DERIVE,
-     * CKM_TLS12_MASTER_KEY_DERIVE_DH and CKM_TLS_MAC are new for v2.40 */
+    public static final long  CKM_WTLS_PRE_MASTER_KEY_GEN         = 0x000003D0L;
+    public static final long  CKM_WTLS_MASTER_KEY_DERIVE          = 0x000003D1L;
+    public static final long  CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   = 0x000003D2L;
+    public static final long  CKM_WTLS_PRF                        = 0x000003D3L;
+    public static final long  CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  = 0x000003D4L;
+    public static final long  CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  = 0x000003D5L;
+
+    public static final long  CKM_TLS10_MAC_SERVER           = 0x000003D6L;
+    public static final long  CKM_TLS10_MAC_CLIENT           = 0x000003D7L;
+    public static final long  CKM_TLS12_MAC                  = 0x000003D8L;
+    public static final long  CKM_TLS12_KDF                  = 0x000003D9L;
+
     public static final long  CKM_TLS12_MASTER_KEY_DERIVE    = 0x000003E0L;
     public static final long  CKM_TLS12_KEY_AND_MAC_DERIVE   = 0x000003E1L;
     public static final long  CKM_TLS12_MASTER_KEY_DERIVE_DH = 0x000003E2L;
+    public static final long  CKM_TLS12_KEY_SAFE_DERIVE      = 0x000003E3L;
     public static final long  CKM_TLS_MAC                    = 0x000003E4L;
+    public static final long  CKM_TLS_KDF                    = 0x000003E5L;
 
     public static final long  CKM_KEY_WRAP_LYNKS             = 0x00000400L;
     public static final long  CKM_KEY_WRAP_SET_OAEP          = 0x00000401L;
 
-    /* Fortezza mechanisms */
+    public static final long  CKM_CMS_SIG                    = 0x00000500L;
+    public static final long  CKM_KIP_DERIVE                 = 0x00000510L;
+    public static final long  CKM_KIP_WRAP                   = 0x00000511L;
+    public static final long  CKM_KIP_MAC                    = 0x00000512L;
+
+    public static final long  CKM_CAMELLIA_KEY_GEN           = 0x00000550L;
+    public static final long  CKM_CAMELLIA_ECB               = 0x00000551L;
+    public static final long  CKM_CAMELLIA_CBC               = 0x00000552L;
+    public static final long  CKM_CAMELLIA_MAC               = 0x00000553L;
+    public static final long  CKM_CAMELLIA_MAC_GENERAL       = 0x00000554L;
+    public static final long  CKM_CAMELLIA_CBC_PAD           = 0x00000555L;
+    public static final long  CKM_CAMELLIA_ECB_ENCRYPT_DATA  = 0x00000556L;
+    public static final long  CKM_CAMELLIA_CBC_ENCRYPT_DATA  = 0x00000557L;
+    public static final long  CKM_CAMELLIA_CTR               = 0x00000558L;
+
+    public static final long  CKM_ARIA_KEY_GEN               = 0x00000560L;
+    public static final long  CKM_ARIA_ECB                   = 0x00000561L;
+    public static final long  CKM_ARIA_CBC                   = 0x00000562L;
+    public static final long  CKM_ARIA_MAC                   = 0x00000563L;
+    public static final long  CKM_ARIA_MAC_GENERAL           = 0x00000564L;
+    public static final long  CKM_ARIA_CBC_PAD               = 0x00000565L;
+    public static final long  CKM_ARIA_ECB_ENCRYPT_DATA      = 0x00000566L;
+    public static final long  CKM_ARIA_CBC_ENCRYPT_DATA      = 0x00000567L;
+
+    public static final long  CKM_SEED_KEY_GEN               = 0x00000650L;
+    public static final long  CKM_SEED_ECB                   = 0x00000651L;
+    public static final long  CKM_SEED_CBC                   = 0x00000652L;
+    public static final long  CKM_SEED_MAC                   = 0x00000653L;
+    public static final long  CKM_SEED_MAC_GENERAL           = 0x00000654L;
+    public static final long  CKM_SEED_CBC_PAD               = 0x00000655L;
+    public static final long  CKM_SEED_ECB_ENCRYPT_DATA      = 0x00000656L;
+    public static final long  CKM_SEED_CBC_ENCRYPT_DATA      = 0x00000657L;
+
     public static final long  CKM_SKIPJACK_KEY_GEN           = 0x00001000L;
     public static final long  CKM_SKIPJACK_ECB64             = 0x00001001L;
     public static final long  CKM_SKIPJACK_CBC64             = 0x00001002L;
@@ -650,6 +704,7 @@
     public static final long  CKM_SKIPJACK_RELAYX            = 0x0000100AL;
     public static final long  CKM_KEA_KEY_PAIR_GEN           = 0x00001010L;
     public static final long  CKM_KEA_KEY_DERIVE             = 0x00001011L;
+    public static final long  CKM_KEA_DERIVE                 = 0x00001012L;
     public static final long  CKM_FORTEZZA_TIMESTAMP         = 0x00001020L;
     public static final long  CKM_BATON_KEY_GEN              = 0x00001030L;
     public static final long  CKM_BATON_ECB128               = 0x00001031L;
@@ -659,20 +714,24 @@
     public static final long  CKM_BATON_SHUFFLE              = 0x00001035L;
     public static final long  CKM_BATON_WRAP                 = 0x00001036L;
 
-    /* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,
-     * CKM_EC_KEY_PAIR_GEN is preferred */
-    public static final long  CKM_ECDSA_KEY_PAIR_GEN         = 0x00001040L;
+    public static final long  CKM_ECDSA_KEY_PAIR_GEN /*deprecated*/
+                                                             = 0x00001040L;
     public static final long  CKM_EC_KEY_PAIR_GEN            = 0x00001040L;
 
     public static final long  CKM_ECDSA                      = 0x00001041L;
     public static final long  CKM_ECDSA_SHA1                 = 0x00001042L;
+    public static final long  CKM_ECDSA_SHA224               = 0x00001043L;
+    public static final long  CKM_ECDSA_SHA256               = 0x00001044L;
+    public static final long  CKM_ECDSA_SHA384               = 0x00001045L;
+    public static final long  CKM_ECDSA_SHA512               = 0x00001046L;
 
-    /* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE
-     * are new for v2.11 */
     public static final long  CKM_ECDH1_DERIVE               = 0x00001050L;
     public static final long  CKM_ECDH1_COFACTOR_DERIVE      = 0x00001051L;
     public static final long  CKM_ECMQV_DERIVE               = 0x00001052L;
 
+    public static final long  CKM_ECDH_AES_KEY_WRAP          = 0x00001053L;
+    public static final long  CKM_RSA_AES_KEY_WRAP           = 0x00001054L;
+
     public static final long  CKM_JUNIPER_KEY_GEN            = 0x00001060L;
     public static final long  CKM_JUNIPER_ECB128             = 0x00001061L;
     public static final long  CKM_JUNIPER_CBC128             = 0x00001062L;
@@ -681,70 +740,79 @@
     public static final long  CKM_JUNIPER_WRAP               = 0x00001065L;
     public static final long  CKM_FASTHASH                   = 0x00001070L;
 
-    /* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,
-     * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,
-     * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are
-     * new for v2.11 */
     public static final long  CKM_AES_KEY_GEN                = 0x00001080L;
     public static final long  CKM_AES_ECB                    = 0x00001081L;
     public static final long  CKM_AES_CBC                    = 0x00001082L;
     public static final long  CKM_AES_MAC                    = 0x00001083L;
     public static final long  CKM_AES_MAC_GENERAL            = 0x00001084L;
     public static final long  CKM_AES_CBC_PAD                = 0x00001085L;
-    // v2.20
+    public static final long  CKM_AES_CTR                    = 0x00001086L;
+    public static final long  CKM_AES_GCM                    = 0x00001087L;
+    public static final long  CKM_AES_CCM                    = 0x00001088L;
+    public static final long  CKM_AES_CTS                    = 0x00001089L;
+    public static final long  CKM_AES_CMAC                   = 0x0000108AL;
+    public static final long  CKM_AES_CMAC_GENERAL           = 0x0000108BL;
+
+    public static final long  CKM_AES_XCBC_MAC               = 0x0000108CL;
+    public static final long  CKM_AES_XCBC_MAC_96            = 0x0000108DL;
+    public static final long  CKM_AES_GMAC                   = 0x0000108EL;
+
     public static final long  CKM_BLOWFISH_KEY_GEN           = 0x00001090L;
     public static final long  CKM_BLOWFISH_CBC               = 0x00001091L;
+    public static final long  CKM_TWOFISH_KEY_GEN            = 0x00001092L;
+    public static final long  CKM_TWOFISH_CBC                = 0x00001093L;
+    public static final long  CKM_BLOWFISH_CBC_PAD           = 0x00001094L;
+    public static final long  CKM_TWOFISH_CBC_PAD            = 0x00001095L;
+
+    public static final long  CKM_DES_ECB_ENCRYPT_DATA       = 0x00001100L;
+    public static final long  CKM_DES_CBC_ENCRYPT_DATA       = 0x00001101L;
+    public static final long  CKM_DES3_ECB_ENCRYPT_DATA      = 0x00001102L;
+    public static final long  CKM_DES3_CBC_ENCRYPT_DATA      = 0x00001103L;
+    public static final long  CKM_AES_ECB_ENCRYPT_DATA       = 0x00001104L;
+    public static final long  CKM_AES_CBC_ENCRYPT_DATA       = 0x00001105L;
+
+    public static final long  CKM_GOSTR3410_KEY_PAIR_GEN     = 0x00001200L;
+    public static final long  CKM_GOSTR3410                  = 0x00001201L;
+    public static final long  CKM_GOSTR3410_WITH_GOSTR3411   = 0x00001202L;
+    public static final long  CKM_GOSTR3410_KEY_WRAP         = 0x00001203L;
+    public static final long  CKM_GOSTR3410_DERIVE           = 0x00001204L;
+    public static final long  CKM_GOSTR3411                  = 0x00001210L;
+    public static final long  CKM_GOSTR3411_HMAC             = 0x00001211L;
+    public static final long  CKM_GOST28147_KEY_GEN          = 0x00001220L;
+    public static final long  CKM_GOST28147_ECB              = 0x00001221L;
+    public static final long  CKM_GOST28147                  = 0x00001222L;
+    public static final long  CKM_GOST28147_MAC              = 0x00001223L;
+    public static final long  CKM_GOST28147_KEY_WRAP         = 0x00001224L;
+
     public static final long  CKM_DSA_PARAMETER_GEN          = 0x00002000L;
     public static final long  CKM_DH_PKCS_PARAMETER_GEN      = 0x00002001L;
     public static final long  CKM_X9_42_DH_PARAMETER_GEN     = 0x00002002L;
+    public static final long  CKM_DSA_PROBABLISTIC_PARAMETER_GEN = 0x00002003L;
+    public static final long  CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN = 0x00002004L;
+
+    public static final long  CKM_AES_OFB                    = 0x00002104L;
+    public static final long  CKM_AES_CFB64                  = 0x00002105L;
+    public static final long  CKM_AES_CFB8                   = 0x00002106L;
+    public static final long  CKM_AES_CFB128                 = 0x00002107L;
+    public static final long  CKM_AES_CFB1                   = 0x00002108L;
+    public static final long  CKM_AES_KEY_WRAP               = 0x00002109L;
+    public static final long  CKM_AES_KEY_WRAP_PAD           = 0x0000210AL;
+
+    public static final long  CKM_RSA_PKCS_TPM_1_1           = 0x00004001L;
+    public static final long  CKM_RSA_PKCS_OAEP_TPM_1_1      = 0x00004002L;
 
     public static final long  CKM_VENDOR_DEFINED             = 0x80000000L;
 
-    // new for v2.20 amendment 3
-    public static final long  CKM_SHA224                     = 0x00000255L;
-    public static final long  CKM_SHA224_HMAC                = 0x00000256L;
-    public static final long  CKM_SHA224_HMAC_GENERAL        = 0x00000257L;
-    public static final long  CKM_SHA224_KEY_DERIVATION      = 0x00000396L;
-    public static final long  CKM_SHA224_RSA_PKCS            = 0x00000046L;
-    public static final long  CKM_SHA224_RSA_PKCS_PSS        = 0x00000047L;
-    public static final long  CKM_AES_CTR                    = 0x00001086L;
-    /*
-    public static final long  CKM_CAMELLIA_KEY_GEN           = 0x00000550L;
-    public static final long  CKM_CAMELLIA_ECB               = 0x00000551L;
-    public static final long  CKM_CAMELLIA_CBC               = 0x00000552L;
-    public static final long  CKM_CAMELLIA_MAC               = 0x00000553L;
-    public static final long  CKM_CAMELLIA_MAC_GENERAL       = 0x00000554L;
-    public static final long  CKM_CAMELLIA_CBC_PAD           = 0x00000555L;
-    public static final long  CKM_CAMELLIA_ECB_ENCRYPT_DATA  = 0x00000556L;
-    public static final long  CKM_CAMELLIA_CBC_ENCRYPT_DATA  = 0x00000557L;
-    public static final long  CKM_CAMELLIA_CTR               = 0x00000558L;
-    public static final long  CKM_ARIA_KEY_GEN               = 0x00000560L;
-    public static final long  CKM_ARIA_ECB                   = 0x00000561L;
-    public static final long  CKM_ARIA_CBC                   = 0x00000562L;
-    public static final long  CKM_ARIA_MAC                   = 0x00000563L;
-    public static final long  CKM_ARIA_MAC_GENERAL           = 0x00000564L;
-    public static final long  CKM_ARIA_CBC_PAD               = 0x00000565L;
-    public static final long  CKM_ARIA_ECB_ENCRYPT_DATA      = 0x00000566L;
-    public static final long  CKM_ARIA_CBC_ENCRYPT_DATA      = 0x00000567L;
-    */
-
     // NSS private
     public static final long  CKM_NSS_TLS_PRF_GENERAL        = 0x80000373L;
 
-    // ids for our pseudo mechanisms SecureRandom and KeyStore
+    // internal ids for our pseudo mechanisms SecureRandom and KeyStore
     public static final long  PCKM_SECURERANDOM              = 0x7FFFFF20L;
     public static final long  PCKM_KEYSTORE                  = 0x7FFFFF21L;
 
-    /* The flags are defined as follows:
-     *      Bit Flag               Mask        Meaning */
-    /* performed by HW */
+    /* The flags specify whether or not a mechanism can be used for a
+     * particular task */
     public static final long  CKF_HW                 = 0x00000001L;
-
-    /* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN,
-     * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER,
-     * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP,
-     * and CKF_DERIVE are new for v2.0.  They specify whether or not
-     * a mechanism can be used for a particular task */
     public static final long  CKF_ENCRYPT            = 0x00000100L;
     public static final long  CKF_DECRYPT            = 0x00000200L;
     public static final long  CKF_DIGEST             = 0x00000400L;
@@ -758,152 +826,141 @@
     public static final long  CKF_UNWRAP             = 0x00040000L;
     public static final long  CKF_DERIVE             = 0x00080000L;
 
-    /* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE,
-     * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They
-     * describe a token's EC capabilities not available in mechanism
-     * information. */
-    public static final long  CKF_EC_F_P              = 0x00100000L;
-    public static final long  CKF_EC_F_2M           = 0x00200000L;
-    public static final long  CKF_EC_ECPARAMETERS   = 0x00400000L;
-    public static final long  CKF_EC_NAMEDCURVE     = 0x00800000L;
-    public static final long  CKF_EC_UNCOMPRESS     = 0x01000000L;
-    public static final long  CKF_EC_COMPRESS       = 0x02000000L;
+    /* Describe a token's EC capabilities not available in mechanism
+     * information.
+     */
+    public static final long  CKF_EC_F_P             = 0x00100000L;
+    public static final long  CKF_EC_F_2M            = 0x00200000L;
+    public static final long  CKF_EC_ECPARAMETERS    = 0x00400000L;
+    public static final long  CKF_EC_NAMEDCURVE      = 0x00800000L;
+    public static final long  CKF_EC_UNCOMPRESS      = 0x01000000L;
+    public static final long  CKF_EC_COMPRESS        = 0x02000000L;
 
-    /* FALSE for 2.01 */
     public static final long  CKF_EXTENSION          = 0x80000000L;
 
 
-    /* CK_RV is a value that identifies the return value of a
-     * Cryptoki function */
-    /* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */
-    public static final long  CKR_OK                                = 0x00000000L;
-    public static final long  CKR_CANCEL                            = 0x00000001L;
-    public static final long  CKR_HOST_MEMORY                       = 0x00000002L;
-    public static final long  CKR_SLOT_ID_INVALID                   = 0x00000003L;
+    /* Identifies the return value of a Cryptoki function */
+    public static final long  CKR_OK                 = 0x00000000L;
+    public static final long  CKR_CANCEL             = 0x00000001L;
+    public static final long  CKR_HOST_MEMORY        = 0x00000002L;
+    public static final long  CKR_SLOT_ID_INVALID    = 0x00000003L;
 
-    /* CKR_FLAGS_INVALID was removed for v2.0 */
+    public static final long  CKR_GENERAL_ERROR      = 0x00000005L;
+    public static final long  CKR_FUNCTION_FAILED    = 0x00000006L;
 
-    /* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */
-    public static final long  CKR_GENERAL_ERROR                     = 0x00000005L;
-    public static final long  CKR_FUNCTION_FAILED                   = 0x00000006L;
+    public static final long  CKR_ARGUMENTS_BAD      = 0x00000007L;
+    public static final long  CKR_NO_EVENT           = 0x00000008L;
+    public static final long  CKR_NEED_TO_CREATE_THREADS
+                                                     = 0x00000009L;
+    public static final long  CKR_CANT_LOCK          = 0x0000000AL;
 
-    /* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS,
-     * and CKR_CANT_LOCK are new for v2.01 */
-    public static final long  CKR_ARGUMENTS_BAD                     = 0x00000007L;
-    public static final long  CKR_NO_EVENT                          = 0x00000008L;
-    public static final long  CKR_NEED_TO_CREATE_THREADS            = 0x00000009L;
-    public static final long  CKR_CANT_LOCK                         = 0x0000000AL;
+    public static final long  CKR_ATTRIBUTE_READ_ONLY       = 0x00000010L;
+    public static final long  CKR_ATTRIBUTE_SENSITIVE       = 0x00000011L;
+    public static final long  CKR_ATTRIBUTE_TYPE_INVALID    = 0x00000012L;
+    public static final long  CKR_ATTRIBUTE_VALUE_INVALID   = 0x00000013L;
+    public static final long  CKR_ACTION_PROHIBITED         = 0x0000001BL;
 
-    public static final long  CKR_ATTRIBUTE_READ_ONLY               = 0x00000010L;
-    public static final long  CKR_ATTRIBUTE_SENSITIVE               = 0x00000011L;
-    public static final long  CKR_ATTRIBUTE_TYPE_INVALID            = 0x00000012L;
-    public static final long  CKR_ATTRIBUTE_VALUE_INVALID           = 0x00000013L;
-    public static final long  CKR_DATA_INVALID                      = 0x00000020L;
-    public static final long  CKR_DATA_LEN_RANGE                    = 0x00000021L;
-    public static final long  CKR_DEVICE_ERROR                      = 0x00000030L;
-    public static final long  CKR_DEVICE_MEMORY                     = 0x00000031L;
-    public static final long  CKR_DEVICE_REMOVED                    = 0x00000032L;
-    public static final long  CKR_ENCRYPTED_DATA_INVALID            = 0x00000040L;
-    public static final long  CKR_ENCRYPTED_DATA_LEN_RANGE          = 0x00000041L;
-    public static final long  CKR_FUNCTION_CANCELED                 = 0x00000050L;
-    public static final long  CKR_FUNCTION_NOT_PARALLEL             = 0x00000051L;
+    public static final long  CKR_DATA_INVALID              = 0x00000020L;
+    public static final long  CKR_DATA_LEN_RANGE            = 0x00000021L;
+    public static final long  CKR_DEVICE_ERROR              = 0x00000030L;
+    public static final long  CKR_DEVICE_MEMORY             = 0x00000031L;
+    public static final long  CKR_DEVICE_REMOVED            = 0x00000032L;
+    public static final long  CKR_ENCRYPTED_DATA_INVALID    = 0x00000040L;
+    public static final long  CKR_ENCRYPTED_DATA_LEN_RANGE  = 0x00000041L;
+    public static final long  CKR_FUNCTION_CANCELED         = 0x00000050L;
+    public static final long  CKR_FUNCTION_NOT_PARALLEL     = 0x00000051L;
 
-    /* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */
-    public static final long  CKR_FUNCTION_NOT_SUPPORTED            = 0x00000054L;
+    public static final long  CKR_FUNCTION_NOT_SUPPORTED    = 0x00000054L;
 
-    public static final long  CKR_KEY_HANDLE_INVALID                = 0x00000060L;
+    public static final long  CKR_KEY_HANDLE_INVALID        = 0x00000060L;
+
+    public static final long  CKR_KEY_SIZE_RANGE            = 0x00000062L;
+    public static final long  CKR_KEY_TYPE_INCONSISTENT     = 0x00000063L;
 
-    /* CKR_KEY_SENSITIVE was removed for v2.0 */
-
-    public static final long  CKR_KEY_SIZE_RANGE                    = 0x00000062L;
-    public static final long  CKR_KEY_TYPE_INCONSISTENT             = 0x00000063L;
+    public static final long  CKR_KEY_NOT_NEEDED                 = 0x00000064L;
+    public static final long  CKR_KEY_CHANGED                    = 0x00000065L;
+    public static final long  CKR_KEY_NEEDED                     = 0x00000066L;
+    public static final long  CKR_KEY_INDIGESTIBLE               = 0x00000067L;
+    public static final long  CKR_KEY_FUNCTION_NOT_PERMITTED     = 0x00000068L;
+    public static final long  CKR_KEY_NOT_WRAPPABLE              = 0x00000069L;
+    public static final long  CKR_KEY_UNEXTRACTABLE              = 0x0000006AL;
 
-    /* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED,
-     * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED,
-     * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for
-     * v2.0 */
-    public static final long  CKR_KEY_NOT_NEEDED                    = 0x00000064L;
-    public static final long  CKR_KEY_CHANGED                       = 0x00000065L;
-    public static final long  CKR_KEY_NEEDED                        = 0x00000066L;
-    public static final long  CKR_KEY_INDIGESTIBLE                  = 0x00000067L;
-    public static final long  CKR_KEY_FUNCTION_NOT_PERMITTED        = 0x00000068L;
-    public static final long  CKR_KEY_NOT_WRAPPABLE                 = 0x00000069L;
-    public static final long  CKR_KEY_UNEXTRACTABLE                 = 0x0000006AL;
+    public static final long  CKR_MECHANISM_INVALID              = 0x00000070L;
+    public static final long  CKR_MECHANISM_PARAM_INVALID        = 0x00000071L;
 
-    public static final long  CKR_MECHANISM_INVALID                 = 0x00000070L;
-    public static final long  CKR_MECHANISM_PARAM_INVALID           = 0x00000071L;
+    public static final long  CKR_OBJECT_HANDLE_INVALID          = 0x00000082L;
+    public static final long  CKR_OPERATION_ACTIVE               = 0x00000090L;
+    public static final long  CKR_OPERATION_NOT_INITIALIZED      = 0x00000091L;
+    public static final long  CKR_PIN_INCORRECT                  = 0x000000A0L;
+    public static final long  CKR_PIN_INVALID                    = 0x000000A1L;
+    public static final long  CKR_PIN_LEN_RANGE                  = 0x000000A2L;
+
+    public static final long  CKR_PIN_EXPIRED                    = 0x000000A3L;
+    public static final long  CKR_PIN_LOCKED                     = 0x000000A4L;
 
-    /* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID
-     * were removed for v2.0 */
-    public static final long  CKR_OBJECT_HANDLE_INVALID             = 0x00000082L;
-    public static final long  CKR_OPERATION_ACTIVE                  = 0x00000090L;
-    public static final long  CKR_OPERATION_NOT_INITIALIZED         = 0x00000091L;
-    public static final long  CKR_PIN_INCORRECT                     = 0x000000A0L;
-    public static final long  CKR_PIN_INVALID                       = 0x000000A1L;
-    public static final long  CKR_PIN_LEN_RANGE                     = 0x000000A2L;
+    public static final long  CKR_SESSION_CLOSED                 = 0x000000B0L;
+    public static final long  CKR_SESSION_COUNT                  = 0x000000B1L;
+    public static final long  CKR_SESSION_HANDLE_INVALID         = 0x000000B3L;
+    public static final long  CKR_SESSION_PARALLEL_NOT_SUPPORTED = 0x000000B4L;
+    public static final long  CKR_SESSION_READ_ONLY              = 0x000000B5L;
+    public static final long  CKR_SESSION_EXISTS                 = 0x000000B6L;
+
+    public static final long  CKR_SESSION_READ_ONLY_EXISTS       = 0x000000B7L;
+    public static final long  CKR_SESSION_READ_WRITE_SO_EXISTS   = 0x000000B8L;
 
-    /* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */
-    public static final long  CKR_PIN_EXPIRED                       = 0x000000A3L;
-    public static final long  CKR_PIN_LOCKED                        = 0x000000A4L;
+    public static final long  CKR_SIGNATURE_INVALID              = 0x000000C0L;
+    public static final long  CKR_SIGNATURE_LEN_RANGE            = 0x000000C1L;
+    public static final long  CKR_TEMPLATE_INCOMPLETE            = 0x000000D0L;
+    public static final long  CKR_TEMPLATE_INCONSISTENT          = 0x000000D1L;
+    public static final long  CKR_TOKEN_NOT_PRESENT              = 0x000000E0L;
+    public static final long  CKR_TOKEN_NOT_RECOGNIZED           = 0x000000E1L;
+    public static final long  CKR_TOKEN_WRITE_PROTECTED          = 0x000000E2L;
+    public static final long  CKR_UNWRAPPING_KEY_HANDLE_INVALID  = 0x000000F0L;
+    public static final long  CKR_UNWRAPPING_KEY_SIZE_RANGE      = 0x000000F1L;
+    public static final long  CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT
+                                                                 = 0x000000F2L;
+    public static final long  CKR_USER_ALREADY_LOGGED_IN         = 0x00000100L;
+    public static final long  CKR_USER_NOT_LOGGED_IN             = 0x00000101L;
+    public static final long  CKR_USER_PIN_NOT_INITIALIZED       = 0x00000102L;
+    public static final long  CKR_USER_TYPE_INVALID              = 0x00000103L;
 
-    public static final long  CKR_SESSION_CLOSED                    = 0x000000B0L;
-    public static final long  CKR_SESSION_COUNT                     = 0x000000B1L;
-    public static final long  CKR_SESSION_HANDLE_INVALID            = 0x000000B3L;
-    public static final long  CKR_SESSION_PARALLEL_NOT_SUPPORTED    = 0x000000B4L;
-    public static final long  CKR_SESSION_READ_ONLY                 = 0x000000B5L;
-    public static final long  CKR_SESSION_EXISTS                    = 0x000000B6L;
-
-    /* CKR_SESSION_READ_ONLY_EXISTS and
-     * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */
-    public static final long  CKR_SESSION_READ_ONLY_EXISTS          = 0x000000B7L;
-    public static final long  CKR_SESSION_READ_WRITE_SO_EXISTS      = 0x000000B8L;
+    public static final long  CKR_USER_ANOTHER_ALREADY_LOGGED_IN = 0x00000104L;
+    public static final long  CKR_USER_TOO_MANY_TYPES            = 0x00000105L;
 
-    public static final long  CKR_SIGNATURE_INVALID                 = 0x000000C0L;
-    public static final long  CKR_SIGNATURE_LEN_RANGE               = 0x000000C1L;
-    public static final long  CKR_TEMPLATE_INCOMPLETE               = 0x000000D0L;
-    public static final long  CKR_TEMPLATE_INCONSISTENT             = 0x000000D1L;
-    public static final long  CKR_TOKEN_NOT_PRESENT                 = 0x000000E0L;
-    public static final long  CKR_TOKEN_NOT_RECOGNIZED              = 0x000000E1L;
-    public static final long  CKR_TOKEN_WRITE_PROTECTED             = 0x000000E2L;
-    public static final long  CKR_UNWRAPPING_KEY_HANDLE_INVALID     = 0x000000F0L;
-    public static final long  CKR_UNWRAPPING_KEY_SIZE_RANGE         = 0x000000F1L;
-    public static final long  CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT  = 0x000000F2L;
-    public static final long  CKR_USER_ALREADY_LOGGED_IN            = 0x00000100L;
-    public static final long  CKR_USER_NOT_LOGGED_IN                = 0x00000101L;
-    public static final long  CKR_USER_PIN_NOT_INITIALIZED          = 0x00000102L;
-    public static final long  CKR_USER_TYPE_INVALID                 = 0x00000103L;
+    public static final long  CKR_WRAPPED_KEY_INVALID            = 0x00000110L;
+    public static final long  CKR_WRAPPED_KEY_LEN_RANGE          = 0x00000112L;
+    public static final long  CKR_WRAPPING_KEY_HANDLE_INVALID    = 0x00000113L;
+    public static final long  CKR_WRAPPING_KEY_SIZE_RANGE        = 0x00000114L;
+    public static final long  CKR_WRAPPING_KEY_TYPE_INCONSISTENT = 0x00000115L;
+    public static final long  CKR_RANDOM_SEED_NOT_SUPPORTED      = 0x00000120L;
 
-    /* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES
-     * are new to v2.01 */
-    public static final long  CKR_USER_ANOTHER_ALREADY_LOGGED_IN    = 0x00000104L;
-    public static final long  CKR_USER_TOO_MANY_TYPES               = 0x00000105L;
+    public static final long  CKR_RANDOM_NO_RNG                  = 0x00000121L;
+
+    public static final long  CKR_DOMAIN_PARAMS_INVALID          = 0x00000130L;
+
+    public static final long  CKR_CURVE_NOT_SUPPORTED            = 0x00000140L;
 
-    public static final long  CKR_WRAPPED_KEY_INVALID               = 0x00000110L;
-    public static final long  CKR_WRAPPED_KEY_LEN_RANGE             = 0x00000112L;
-    public static final long  CKR_WRAPPING_KEY_HANDLE_INVALID       = 0x00000113L;
-    public static final long  CKR_WRAPPING_KEY_SIZE_RANGE           = 0x00000114L;
-    public static final long  CKR_WRAPPING_KEY_TYPE_INCONSISTENT    = 0x00000115L;
-    public static final long  CKR_RANDOM_SEED_NOT_SUPPORTED         = 0x00000120L;
+    public static final long  CKR_BUFFER_TOO_SMALL               = 0x00000150L;
+    public static final long  CKR_SAVED_STATE_INVALID            = 0x00000160L;
+    public static final long  CKR_INFORMATION_SENSITIVE          = 0x00000170L;
+    public static final long  CKR_STATE_UNSAVEABLE               = 0x00000180L;
 
-    /* These are new to v2.0 */
-    public static final long  CKR_RANDOM_NO_RNG                     = 0x00000121L;
-
-    /* These are new to v2.11 */
-    public static final long  CKR_DOMAIN_PARAMS_INVALID             = 0x00000130L;
+    public static final long  CKR_CRYPTOKI_NOT_INITIALIZED       = 0x00000190L;
+    public static final long  CKR_CRYPTOKI_ALREADY_INITIALIZED   = 0x00000191L;
+    public static final long  CKR_MUTEX_BAD                      = 0x000001A0L;
+    public static final long  CKR_MUTEX_NOT_LOCKED               = 0x000001A1L;
 
-    /* These are new to v2.0 */
-    public static final long  CKR_BUFFER_TOO_SMALL                  = 0x00000150L;
-    public static final long  CKR_SAVED_STATE_INVALID               = 0x00000160L;
-    public static final long  CKR_INFORMATION_SENSITIVE             = 0x00000170L;
-    public static final long  CKR_STATE_UNSAVEABLE                  = 0x00000180L;
+    public static final long  CKR_NEW_PIN_MODE                   = 0x000001B0L;
+    public static final long  CKR_NEXT_OTP                       = 0x000001B1L;
 
-    /* These are new to v2.01 */
-    public static final long  CKR_CRYPTOKI_NOT_INITIALIZED          = 0x00000190L;
-    public static final long  CKR_CRYPTOKI_ALREADY_INITIALIZED      = 0x00000191L;
-    public static final long  CKR_MUTEX_BAD                         = 0x000001A0L;
-    public static final long  CKR_MUTEX_NOT_LOCKED                  = 0x000001A1L;
+    public static final long  CKR_EXCEEDED_MAX_ITERATIONS        = 0x000001B5L;
+    public static final long  CKR_FIPS_SELF_TEST_FAILED          = 0x000001B6L;
+    public static final long  CKR_LIBRARY_LOAD_FAILED            = 0x000001B7L;
+    public static final long  CKR_PIN_TOO_WEAK                   = 0x000001B8L;
+    public static final long  CKR_PUBLIC_KEY_INVALID             = 0x000001B9L;
+    public static final long  CKR_FUNCTION_REJECTED              = 0x00000200L;
 
-    public static final long  CKR_VENDOR_DEFINED                    = 0x80000000L;
+    public static final long  CKR_VENDOR_DEFINED                 = 0x80000000L;
 
 
     /* flags: bit flags that provide capabilities of the slot
@@ -916,31 +973,56 @@
     /* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */
     public static final long  CKF_DONT_BLOCK =    1L;
 
-
     /* The following MGFs are defined */
-    public static final long  CKG_MGF1_SHA1       =  0x00000001L;
-    // new for v2.20 amendment 3
+    public static final long  CKG_MGF1_SHA1       = 0x00000001L;
+    public static final long  CKG_MGF1_SHA256     = 0x00000002L;
+    public static final long  CKG_MGF1_SHA384     = 0x00000003L;
+    public static final long  CKG_MGF1_SHA512     = 0x00000004L;
     public static final long  CKG_MGF1_SHA224     = 0x00000005L;
 
     /* The following encoding parameter sources are defined */
     public static final long  CKZ_DATA_SPECIFIED   = 0x00000001L;
 
 
-    /* The following PRFs are defined in PKCS #5 v2.0. */
-    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001L;
-
-
-    /* The following salt value sources are defined in PKCS #5 v2.0. */
-    public static final long CKZ_SALT_SPECIFIED        = 0x00000001L;
-
     /* the following EC Key Derivation Functions are defined */
-    public static final long CKD_NULL                 = 0x00000001L;
-    public static final long CKD_SHA1_KDF             = 0x00000002L;
+    public static final long  CKD_NULL                 = 0x00000001L;
+    public static final long  CKD_SHA1_KDF             = 0x00000002L;
 
     /* the following X9.42 Diffie-Hellman Key Derivation Functions are defined */
-    public static final long CKD_SHA1_KDF_ASN1        = 0x00000003L;
-    public static final long CKD_SHA1_KDF_CONCATENATE = 0x00000004L;
+    public static final long  CKD_SHA1_KDF_ASN1        = 0x00000003L;
+    public static final long  CKD_SHA1_KDF_CONCATENATE = 0x00000004L;
+    public static final long  CKD_SHA224_KDF           = 0x00000005L;
+    public static final long  CKD_SHA256_KDF           = 0x00000006L;
+    public static final long  CKD_SHA384_KDF           = 0x00000007L;
+    public static final long  CKD_SHA512_KDF           = 0x00000008L;
+    public static final long  CKD_CPDIVERSIFY_KDF      = 0x00000009L;
+
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA1        = 0x00000001L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_GOSTR3411   = 0x00000002L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA224      = 0x00000003L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA256      = 0x00000004L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA384      = 0x00000005L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA512      = 0x00000006L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA512_224  = 0x00000007L;
+    public static final long  CKP_PKCS5_PBKD2_HMAC_SHA512_256  = 0x00000008L;
 
+    public static final long  CKZ_SALT_SPECIFIED      = 0x00000001L;
+
+    public static final long  CK_OTP_VALUE            = 0x00000000L;
+    public static final long  CK_OTP_PIN              = 0x00000001L;
+    public static final long  CK_OTP_CHALLENGE        = 0x00000002L;
+    public static final long  CK_OTP_TIME             = 0x00000003L;
+    public static final long  CK_OTP_COUNTER          = 0x00000004L;
+    public static final long  CK_OTP_FLAGS            = 0x00000005L;
+    public static final long  CK_OTP_OUTPUT_LENGTH    = 0x00000006L;
+    public static final long  CK_OTP_OUTPUT_FORMAT    = 0x00000007L;
+
+    public static final long  CKF_NEXT_OTP            = 0x00000001L;
+    public static final long  CKF_EXCLUDE_TIME        = 0x00000002L;
+    public static final long  CKF_EXCLUDE_COUNTER     = 0x00000004L;
+    public static final long  CKF_EXCLUDE_CHALLENGE   = 0x00000008L;
+    public static final long  CKF_EXCLUDE_PIN         = 0x00000010L;
+    public static final long  CKF_USER_FRIENDLY_OTP   = 0x00000020L;
 
     // private NSS attribute (for DSA and DH private keys)
     public static final long  CKA_NETSCAPE_DB         = 0xD5A0DB00L;
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java	Wed Jun 12 10:02:49 2019 +0530
@@ -88,6 +88,7 @@
             0x00000011,
             0x00000012,
             0x00000013,
+            0x0000001B,
             0x00000020,
             0x00000021,
             0x00000030,
@@ -158,6 +159,13 @@
             0x00000191,
             0x000001A0,
             0x000001A1,
+            0x000001B0,
+            0x000001B1,
+            0x000001B5,
+            0x000001B6,
+            0x000001B7,
+            0x000001B8,
+            0x000001B9,
             0x00000200,
             0x80000000,
         };
@@ -176,6 +184,7 @@
             "CKR_ATTRIBUTE_SENSITIVE",
             "CKR_ATTRIBUTE_TYPE_INVALID",
             "CKR_ATTRIBUTE_VALUE_INVALID",
+            "CKR_ACTION_PROHIBITED",
             "CKR_DATA_INVALID",
             "CKR_DATA_LEN_RANGE",
             "CKR_DEVICE_ERROR",
@@ -246,6 +255,13 @@
             "CKR_CRYPTOKI_ALREADY_INITIALIZED",
             "CKR_MUTEX_BAD",
             "CKR_MUTEX_NOT_LOCKED",
+            "CKR_NEW_PIN_MODE",
+            "CKR_NEXT_OTP",
+            "CKR_EXCEEDED_MAX_ITERATIONS",
+            "CKR_FIPS_SELF_TEST_FAILED",
+            "CKR_LIBRARY_LOAD_FAILED",
+            "CKR_PIN_TOO_WEAK",
+            "CKR_PUBLIC_KEY_INVALID",
             "CKR_FUNCTION_REJECTED",
             "CKR_VENDOR_DEFINED",
         };
--- a/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md	Wed Jun 12 10:02:49 2019 +0530
@@ -1,20 +1,32 @@
-## PKCS #11 Cryptographic Token Interface v2.20 Amendment 3 Header Files
+ASIS PKCS #11 Cryptographic Token Interface v2.40
+
+### OASIS PKCS #11 Cryptographic Token Interface License
+```
 
-### PKCS #11 Cryptographic Token Interface License
-<pre>
+Copyright (c) OASIS Open 2016. All Rights Reserved.
 
-License to copy and use this software is granted provided that it is
-identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
-(Cryptoki)" in all material mentioning or referencing this software.
+All capitalized terms in the following text have the meanings assigned to them in the OASIS
+Intellectual Property Rights Policy (the "OASIS IPR Policy"). The full Policy may be found at the
+OASIS website: [http://www.oasis-open.org/policies-guidelines/ipr]
 
-License is also granted to make and use derivative works provided that
-such works are identified as "derived from the RSA Security Inc. PKCS #11
-Cryptographic Token Interface (Cryptoki)" in all material mentioning or
-referencing the derived work.
+This document and translations of it may be copied and furnished to others, and derivative works
+that comment on or otherwise explain it or assist in its implementation may be prepared, copied,
+published, and distributed, in whole or in part, without restriction of any kind, provided that
+the above copyright notice and this section are included on all such copies and derivative works.
+However, this document itself may not be modified in any way, including by removing the copyright
+notice or references to OASIS, except as needed for the purpose of developing any document or
+deliverable produced by an OASIS Technical Committee (in which case the rules applicable to
+copyrights, as set forth in the OASIS IPR Policy, must be followed) or as required to translate it
+into languages other than English.
 
-RSA Security Inc. makes no representations concerning either the
-merchantability of this software or the suitability of this software for
-any particular purpose. It is provided "as is" without express or implied
-warranty of any kind.
+The limited permissions granted above are perpetual and will not be revoked by OASIS or its
+successors or assigns.
 
-</pre>
+This document and the information contained herein is provided on an "AS IS" basis and OASIS
+DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE
+USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. OASIS AND ITS MEMBERS WILL NOT BE LIABLE FOR
+ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THIS DOCUMENT OR
+ANY PART THEREOF.
+
+```
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_convert.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_convert.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -68,7 +68,8 @@
 
 /* declare file private functions */
 
-void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength);
+CK_VOID_PTR jMechParamToCKMechParamPtrSlow(JNIEnv *env, jobject jParam,
+        CK_MECHANISM_TYPE ckMech, CK_ULONG *ckpLength);
 
 
 /*
@@ -425,8 +426,8 @@
     memset(&ckAttribute, 0, sizeof(CK_ATTRIBUTE));
 
     // TBD: what if jAttribute == NULL?!
+    TRACE0("\nDEBUG: jAttributeToCKAttribute");
 
-    TRACE0("\nDEBUG: jAttributeToCKAttribute");
     /* get CK_ATTRIBUTE class */
     TRACE0(", getting attribute object class");
     jAttributeClass = (*env)->GetObjectClass(env, jAttribute);
@@ -437,7 +438,7 @@
     jFieldID = (*env)->GetFieldID(env, jAttributeClass, "type", "J");
     if (jFieldID == NULL) { return ckAttribute; }
     jType = (*env)->GetLongField(env, jAttribute, jFieldID);
-    TRACE1(", type=0x%X", jType);
+    TRACE1(", type=0x%lX", jType);
 
     /* get pValue */
     TRACE0(", getting pValue field");
@@ -450,9 +451,9 @@
     TRACE0(", converting pValue to primitive object");
 
     /* convert the Java pValue object to a CK-type pValue pointer */
-    jObjectToPrimitiveCKObjectPtrPtr(env, jPValue, &(ckAttribute.pValue), &(ckAttribute.ulValueLen));
+    ckAttribute.pValue = jObjectToPrimitiveCKObjectPtr(env, jPValue, &(ckAttribute.ulValueLen));
 
-    TRACE0("\nFINISHED\n");
+    TRACE0("\nDEBUG: jAttributeToCKAttribute FINISHED\n");
 
     return ckAttribute ;
 }
@@ -515,22 +516,19 @@
  *
  * @param env - used to call JNI functions to get the Java classes and objects
  * @param jParam - the Java CK_SSL3_MASTER_KEY_DERIVE_PARAMS object to convert
- * @return - the new CK_SSL3_MASTER_KEY_DERIVE_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_SSL3_MASTER_KEY_DERIVE_PARAMS structure
  */
-CK_SSL3_MASTER_KEY_DERIVE_PARAMS
-jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env,
-        jobject jParam)
+void jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env,
+        jobject jParam, CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckParamPtr)
 {
-    CK_SSL3_MASTER_KEY_DERIVE_PARAMS ckParam;
     jclass jSsl3MasterKeyDeriveParamsClass;
-    memset(&ckParam, 0, sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
     jSsl3MasterKeyDeriveParamsClass =
             (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return ckParam; }
+    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return; }
     masterKeyDeriveParamToCKMasterKeyDeriveParam(env, jParam,
             jSsl3MasterKeyDeriveParamsClass,
-            &ckParam.pVersion, &ckParam.RandomInfo);
-    return ckParam;
+            &(ckParamPtr->pVersion), &(ckParamPtr->RandomInfo));
 }
 
 /*
@@ -539,123 +537,116 @@
  *
  * @param env - used to call JNI functions to get the Java classes and objects
  * @param jParam - the Java CK_TLS12_MASTER_KEY_DERIVE_PARAMS object to convert
- * @return - the new CK_TLS12_MASTER_KEY_DERIVE_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_TLS12_MASTER_KEY_DERIVE_PARAMS structure
  */
-CK_TLS12_MASTER_KEY_DERIVE_PARAMS
-jTls12MasterKeyDeriveParamToCKTls12MasterKeyDeriveParam(JNIEnv *env,
-        jobject jParam)
+void jTls12MasterKeyDeriveParamToCKTls12MasterKeyDeriveParam(JNIEnv *env,
+        jobject jParam, CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR ckParamPtr)
 {
-    CK_TLS12_MASTER_KEY_DERIVE_PARAMS ckParam;
     jclass jTls12MasterKeyDeriveParamsClass;
     jfieldID fieldID;
-    memset(&ckParam, 0, sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS));
     jTls12MasterKeyDeriveParamsClass =
             (*env)->FindClass(env, CLASS_TLS12_MASTER_KEY_DERIVE_PARAMS);
-    if (jTls12MasterKeyDeriveParamsClass == NULL) { return ckParam; }
+    if (jTls12MasterKeyDeriveParamsClass == NULL) { return; }
     masterKeyDeriveParamToCKMasterKeyDeriveParam(env, jParam,
-            jTls12MasterKeyDeriveParamsClass, &ckParam.pVersion,
-            &ckParam.RandomInfo);
+            jTls12MasterKeyDeriveParamsClass, &ckParamPtr->pVersion,
+            &ckParamPtr->RandomInfo);
     fieldID = (*env)->GetFieldID(env,
             jTls12MasterKeyDeriveParamsClass, "prfHashMechanism", "J");
     if (fieldID != NULL) {
         jlong prfHashMechanism =
                 (*env)->GetLongField(env, jParam, fieldID);
-        ckParam.prfHashMechanism = (CK_MECHANISM_TYPE)prfHashMechanism;
+        ckParamPtr->prfHashMechanism = (CK_MECHANISM_TYPE)prfHashMechanism;
     }
-    return ckParam;
 }
 
 /*
  * converts the Java CK_TLS_PRF_PARAMS object to a CK_TLS_PRF_PARAMS structure
  */
-CK_TLS_PRF_PARAMS jTlsPrfParamsToCKTlsPrfParam(JNIEnv *env, jobject jParam)
+void jTlsPrfParamsToCKTlsPrfParam(JNIEnv *env, jobject jParam,
+CK_TLS_PRF_PARAMS_PTR ckParamPtr)
 {
     jclass jTlsPrfParamsClass;
-    CK_TLS_PRF_PARAMS ckParam;
     jfieldID fieldID;
     jobject jSeed, jLabel, jOutput;
-    memset(&ckParam, 0, sizeof(CK_TLS_PRF_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_TLS_PRF_PARAMS));
 
     // TBD: what if jParam == NULL?!
 
     /* get pSeed */
     jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
-    if (jTlsPrfParamsClass == NULL) { return ckParam; }
+    if (jTlsPrfParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pSeed", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSeed = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pLabel */
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pLabel", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jLabel = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pOutput */
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pOutput", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jOutput = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    jByteArrayToCKByteArray(env, jSeed, &(ckParam.pSeed), &(ckParam.ulSeedLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jByteArrayToCKByteArray(env, jLabel, &(ckParam.pLabel), &(ckParam.ulLabelLen));
+    jByteArrayToCKByteArray(env, jSeed, &(ckParamPtr->pSeed), &(ckParamPtr->ulSeedLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jByteArrayToCKByteArray(env, jLabel, &(ckParamPtr->pLabel), &(ckParamPtr->ulLabelLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSeed);
-        return ckParam;
+        free(ckParamPtr->pSeed);
+        return;
     }
-    ckParam.pulOutputLen = malloc(sizeof(CK_ULONG));
-    if (ckParam.pulOutputLen == NULL) {
-        free(ckParam.pSeed);
-        free(ckParam.pLabel);
+    ckParamPtr->pulOutputLen = malloc(sizeof(CK_ULONG));
+    if (ckParamPtr->pulOutputLen == NULL) {
+        free(ckParamPtr->pSeed);
+        free(ckParamPtr->pLabel);
         throwOutOfMemoryError(env, 0);
-        return ckParam;
+        return;
     }
-    jByteArrayToCKByteArray(env, jOutput, &(ckParam.pOutput), ckParam.pulOutputLen);
+    jByteArrayToCKByteArray(env, jOutput, &(ckParamPtr->pOutput), ckParamPtr->pulOutputLen);
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSeed);
-        free(ckParam.pLabel);
-        free(ckParam.pulOutputLen);
-        return ckParam;
+        free(ckParamPtr->pSeed);
+        free(ckParamPtr->pLabel);
+        free(ckParamPtr->pOutput);
+        return;
     }
-
-    return ckParam ;
 }
 
 /*
  * converts the Java CK_TLS_MAC_PARAMS object to a CK_TLS_MAC_PARAMS structure
  */
-CK_TLS_MAC_PARAMS jTlsMacParamsToCKTlsMacParam(JNIEnv *env, jobject jParam)
+void jTlsMacParamsToCKTlsMacParam(JNIEnv *env, jobject jParam,
+        CK_TLS_MAC_PARAMS_PTR ckParamPtr)
 {
     jclass jTlsMacParamsClass;
-    CK_TLS_MAC_PARAMS ckParam;
     jfieldID fieldID;
     jlong jPrfMechanism, jUlMacLength, jUlServerOrClient;
-    memset(&ckParam, 0, sizeof(CK_TLS_MAC_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_TLS_MAC_PARAMS));
 
     jTlsMacParamsClass = (*env)->FindClass(env, CLASS_TLS_MAC_PARAMS);
-    if (jTlsMacParamsClass == NULL) { return ckParam; }
+    if (jTlsMacParamsClass == NULL) { return; }
 
     /* get prfMechanism */
     fieldID = (*env)->GetFieldID(env, jTlsMacParamsClass, "prfMechanism", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrfMechanism = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulMacLength */
     fieldID = (*env)->GetFieldID(env, jTlsMacParamsClass, "ulMacLength", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jUlMacLength = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulServerOrClient */
     fieldID = (*env)->GetFieldID(env, jTlsMacParamsClass, "ulServerOrClient", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jUlServerOrClient = (*env)->GetLongField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.prfMechanism = jLongToCKULong(jPrfMechanism);
-    ckParam.ulMacLength = jLongToCKULong(jUlMacLength);
-    ckParam.ulServerOrClient = jLongToCKULong(jUlServerOrClient);
-
-    return ckParam;
+    ckParamPtr->prfMechanism = jLongToCKULong(jPrfMechanism);
+    ckParamPtr->ulMacLength = jLongToCKULong(jUlMacLength);
+    ckParamPtr->ulServerOrClient = jLongToCKULong(jUlServerOrClient);
 }
 
 void keyMatParamToCKKeyMatParam(JNIEnv *env, jobject jParam,
@@ -747,7 +738,7 @@
         free(cKKeyMatParamRandomInfo->pClientRandom);
         return;
     }
-    /* allocate memory for pRetrunedKeyMaterial */
+    /* allocate memory for pReturnedKeyMaterial */
     *cKKeyMatParamPReturnedKeyMaterial =
             (CK_SSL3_KEY_MAT_OUT_PTR)malloc(sizeof(CK_SSL3_KEY_MAT_OUT));
     if (*cKKeyMatParamPReturnedKeyMaterial == NULL) {
@@ -789,22 +780,20 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_SSL3_KEY_MAT_PARAMS object to convert
- * @return - the new CK_SSL3_KEY_MAT_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_SSL3_KEY_MAT_PARAMS structure
  */
-CK_SSL3_KEY_MAT_PARAMS
-jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam)
+void jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam,
+        CK_SSL3_KEY_MAT_PARAMS_PTR ckParamPtr)
 {
-    CK_SSL3_KEY_MAT_PARAMS ckParam;
     jclass jSsl3KeyMatParamsClass;
-    memset(&ckParam, 0, sizeof(CK_SSL3_KEY_MAT_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_SSL3_KEY_MAT_PARAMS));
     jSsl3KeyMatParamsClass = (*env)->FindClass(env,
             CLASS_SSL3_KEY_MAT_PARAMS);
-    if (jSsl3KeyMatParamsClass == NULL) { return ckParam; }
+    if (jSsl3KeyMatParamsClass == NULL) { return; }
     keyMatParamToCKKeyMatParam(env, jParam, jSsl3KeyMatParamsClass,
-            &ckParam.ulMacSizeInBits, &ckParam.ulKeySizeInBits,
-            &ckParam.ulIVSizeInBits, &ckParam.bIsExport,
-            &ckParam.RandomInfo, &ckParam.pReturnedKeyMaterial);
-    return ckParam;
+            &(ckParamPtr->ulMacSizeInBits), &(ckParamPtr->ulKeySizeInBits),
+            &(ckParamPtr->ulIVSizeInBits), &(ckParamPtr->bIsExport),
+            &(ckParamPtr->RandomInfo), &(ckParamPtr->pReturnedKeyMaterial));
 }
 
 /*
@@ -813,29 +802,27 @@
  *
  * @param env - used to call JNI functions to get the Java classes and objects
  * @param jParam - the Java CK_TLS12_KEY_MAT_PARAMS object to convert
- * @return - the new CK_TLS12_KEY_MAT_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_TLS12_KEY_MAT_PARAMS structure
  */
-CK_TLS12_KEY_MAT_PARAMS jTls12KeyMatParamToCKTls12KeyMatParam(JNIEnv *env,
-        jobject jParam)
+void jTls12KeyMatParamToCKTls12KeyMatParam(JNIEnv *env,
+        jobject jParam, CK_TLS12_KEY_MAT_PARAMS_PTR ckParamPtr)
 {
-    CK_TLS12_KEY_MAT_PARAMS ckParam;
     jclass jTls12KeyMatParamsClass;
     jfieldID fieldID;
-    memset(&ckParam, 0, sizeof(CK_TLS12_KEY_MAT_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_TLS12_KEY_MAT_PARAMS));
     jTls12KeyMatParamsClass = (*env)->FindClass(env,
             CLASS_TLS12_KEY_MAT_PARAMS);
-    if (jTls12KeyMatParamsClass == NULL) { return ckParam; }
+    if (jTls12KeyMatParamsClass == NULL) { return; }
     keyMatParamToCKKeyMatParam(env, jParam, jTls12KeyMatParamsClass,
-            &ckParam.ulMacSizeInBits, &ckParam.ulKeySizeInBits,
-            &ckParam.ulIVSizeInBits, &ckParam.bIsExport,
-            &ckParam.RandomInfo, &ckParam.pReturnedKeyMaterial);
+            &(ckParamPtr->ulMacSizeInBits), &(ckParamPtr->ulKeySizeInBits),
+            &(ckParamPtr->ulIVSizeInBits), &(ckParamPtr->bIsExport),
+            &(ckParamPtr->RandomInfo), &(ckParamPtr->pReturnedKeyMaterial));
     fieldID = (*env)->GetFieldID(env, jTls12KeyMatParamsClass,
             "prfHashMechanism", "J");
     if (fieldID != NULL) {
         jlong prfHashMechanism = (*env)->GetLongField(env, jParam, fieldID);
-        ckParam.prfHashMechanism = (CK_MECHANISM_TYPE)prfHashMechanism;
+        ckParamPtr->prfHashMechanism = (CK_MECHANISM_TYPE)prfHashMechanism;
     }
-    return ckParam;
 }
 
 /*
@@ -843,10 +830,10 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_AES_CTR_PARAMS object to convert
- * @param ckpParam - pointer to the new CK_AES_CTR_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_AES_CTR_PARAMS structure
  */
 void jAesCtrParamsToCKAesCtrParam(JNIEnv *env, jobject jParam,
-                                  CK_AES_CTR_PARAMS_PTR ckpParam) {
+                                  CK_AES_CTR_PARAMS_PTR ckParamPtr) {
     jclass jAesCtrParamsClass;
     jfieldID fieldID;
     jlong jCounterBits;
@@ -857,6 +844,9 @@
     /* get ulCounterBits */
     jAesCtrParamsClass = (*env)->FindClass(env, CLASS_AES_CTR_PARAMS);
     if (jAesCtrParamsClass == NULL) { return; }
+    if (!(*env)->IsInstanceOf(env, jParam, jAesCtrParamsClass)) {
+        return;
+    }
     fieldID = (*env)->GetFieldID(env, jAesCtrParamsClass, "ulCounterBits", "J");
     if (fieldID == NULL) { return; }
     jCounterBits = (*env)->GetLongField(env, jParam, fieldID);
@@ -867,40 +857,147 @@
     jCb = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckpParam->ulCounterBits = jLongToCKULong(jCounterBits);
+    ckParamPtr->ulCounterBits = jLongToCKULong(jCounterBits);
     jByteArrayToCKByteArray(env, jCb, &ckBytes, &ckTemp);
     if ((*env)->ExceptionCheck(env)) { return; }
     if (ckTemp != 16) {
-        TRACE1("ERROR: WRONG CTR IV LENGTH %d", ckTemp);
+        TRACE1("\nERROR: WRONG CTR IV LENGTH %lu", ckTemp);
     } else {
-        memcpy(ckpParam->cb, ckBytes, ckTemp);
+        memcpy(ckParamPtr->cb, ckBytes, ckTemp);
         free(ckBytes);
     }
 }
 
 /*
- * converts a Java CK_MECHANISM object into a CK_MECHANISM structure
+ * converts the Java CK_GCM_PARAMS object to a CK_GCM_PARAMS structure
+ *
+ * @param env - used to call JNI funktions to get the Java classes and objects
+ * @param jParam - the Java CK_GCM_PARAMS object to convert
+ * @param ckpParam - pointer to the new CK_GCM_PARAMS structure
+ */
+void jGCMParamsToCKGCMParam(JNIEnv *env, jobject jParam,
+                            CK_GCM_PARAMS_PTR ckpParam) {
+    jclass jGcmParamsClass;
+    jfieldID fieldID;
+    jobject jIv, jAad;
+    jlong jTagLen;
+
+    /* get iv */
+    jGcmParamsClass = (*env)->FindClass(env, CLASS_GCM_PARAMS);
+    if (jGcmParamsClass == NULL) { return; }
+    if (!(*env)->IsInstanceOf(env, jParam, jGcmParamsClass)) {
+        return;
+    }
+
+    fieldID = (*env)->GetFieldID(env, jGcmParamsClass, "iv", "[B");
+    if (fieldID == NULL) { return; }
+    jIv = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get aad */
+    fieldID = (*env)->GetFieldID(env, jGcmParamsClass, "aad", "[B");
+    if (fieldID == NULL) { return; }
+    jAad = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get tagLength */
+    fieldID = (*env)->GetFieldID(env, jGcmParamsClass, "tagBits", "J");
+    if (fieldID == NULL) { return; }
+    jTagLen = (*env)->GetLongField(env, jParam, fieldID);
+
+
+    /* populate java values */
+    jByteArrayToCKByteArray(env, jIv, &(ckpParam->pIv), &(ckpParam->ulIvLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+
+    jByteArrayToCKByteArray(env, jAad, &(ckpParam->pAAD), &(ckpParam->ulAADLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+
+    ckpParam->ulTagBits = jLongToCKULong(jTagLen);
+}
+
+/*
+ * converts the Java CK_CCM_PARAMS object to a CK_CCM_PARAMS structure
+ *
+ * @param env - used to call JNI functions to get the Java classes and objects
+ * @param jParam - the Java CK_CCM_PARAMS object to convert
+ * @param ckpParam - pointer to the new CK_CCM_PARAMS structure
+ */
+void jCCMParamsToCKCCMParam(JNIEnv *env, jobject jParam,
+                            CK_CCM_PARAMS_PTR ckpParam) {
+    jclass jCcmParamsClass;
+    jfieldID fieldID;
+    jobject jNonce, jAad;
+    jlong jDataLen, jMacLen;
+
+    /* get iv */
+    jCcmParamsClass = (*env)->FindClass(env, CLASS_CCM_PARAMS);
+    if (jCcmParamsClass == NULL) { return; }
+
+    if (!(*env)->IsInstanceOf(env, jParam, jCcmParamsClass)) {
+        return;
+    }
+    fieldID = (*env)->GetFieldID(env, jCcmParamsClass, "dataLen", "J");
+    if (fieldID == NULL) { return; }
+    jDataLen = (*env)->GetLongField(env, jParam, fieldID);
+
+    fieldID = (*env)->GetFieldID(env, jCcmParamsClass, "nonce", "[B");
+    if (fieldID == NULL) { return; }
+    jNonce = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get aad */
+    fieldID = (*env)->GetFieldID(env, jCcmParamsClass, "aad", "[B");
+    if (fieldID == NULL) { return; }
+    jAad = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get macLen */
+    fieldID = (*env)->GetFieldID(env, jCcmParamsClass, "macLen", "J");
+    if (fieldID == NULL) { return; }
+    jMacLen = (*env)->GetLongField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckpParam->ulDataLen = jLongToCKULong(jDataLen);
+    jByteArrayToCKByteArray(env, jNonce, &(ckpParam->pNonce),
+            &(ckpParam->ulNonceLen));
+    jByteArrayToCKByteArray(env, jAad, &(ckpParam->pAAD),
+            &(ckpParam->ulAADLen));
+    ckpParam->ulMACLen = jLongToCKULong(jMacLen);
+    if ((*env)->ExceptionCheck(env)) { return; }
+}
+
+/*
+ * converts a Java CK_MECHANISM object into a pointer to a CK_MECHANISM
+ * structure. NOTE: CALLER IS RESPONSIBLE FOR FREEING THE RETURNED POINTER
  *
  * @param env - used to call JNI funktions to get the values out of the Java object
  * @param jMechanism - the Java CK_MECHANISM object to convert
- * @return - the new CK_MECHANISM structure
+ * @return - pointer to the new CK_MECHANISM structure
  */
-void jMechanismToCKMechanism(JNIEnv *env, jobject jMechanism, CK_MECHANISM_PTR ckMechanismPtr)
+CK_MECHANISM_PTR jMechanismToCKMechanismPtr(JNIEnv *env, jobject jMech)
 {
-    jlong jMechanismType = (*env)->GetLongField(env, jMechanism, mech_mechanismID);
-    jobject jParameter = (*env)->GetObjectField(env, jMechanism, mech_pParameterID);
-
-    (*ckMechanismPtr).mechanism = jLongToCKULong(jMechanismType);
+    CK_MECHANISM_PTR ckpMech;
+    jlong jMechType = (*env)->GetLongField(env, jMech, mech_mechanismID);
+    jobject jParam = (*env)->GetObjectField(env, jMech, mech_pParameterID);
 
-    /* convert the specific Java mechanism parameter object to a pointer to a CK-type mechanism
-     * structure
+    /* allocate memory for CK_MECHANISM_PTR */
+    ckpMech =  (CK_MECHANISM_PTR) malloc(sizeof(CK_MECHANISM));
+    if (ckpMech == NULL) {
+        throwOutOfMemoryError(env, 0);
+        return NULL;
+    }
+    TRACE1("DEBUG jMechanismToCKMechanismPtr: allocated mech 0x%lX\n", ckpMech);
+
+    ckpMech->mechanism = jLongToCKULong(jMechType);
+
+    /* convert the specific Java mechanism parameter object to a pointer to a
+     *  CK-type mechanism structure
      */
-    if (jParameter == NULL) {
-        (*ckMechanismPtr).pParameter = NULL;
-        (*ckMechanismPtr).ulParameterLen = 0;
+    if (jParam == NULL) {
+        ckpMech->pParameter = NULL;
+        ckpMech->ulParameterLen = 0;
     } else {
-        jMechanismParameterToCKMechanismParameter(env, jParameter, &(*ckMechanismPtr).pParameter, &(*ckMechanismPtr).ulParameterLen);
+        ckpMech->pParameter = jMechParamToCKMechParamPtr(env, jParam,
+            ckpMech->mechanism, &(ckpMech->ulParameterLen));
     }
+    return ckpMech;
 }
 
 /*
@@ -909,15 +1006,14 @@
  * jobject ckAttributeValueToJObject(JNIEnv *env,
  *                                   const CK_ATTRIBUTE_PTR ckpAttribute);
  *
- * void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env,
+ * CK_VOID_PTR jObjectToPrimitiveCKObjectPtr(JNIEnv *env,
  *                                       jobject jObject,
- *                                       CK_VOID_PTR *ckpObjectPtr,
  *                                       CK_ULONG *pLength);
  *
- * void jMechanismParameterToCKMechanismParameter(JNIEnv *env,
- *                                                jobject jParam,
- *                                                CK_VOID_PTR *ckpParamPtr,
- *                                                CK_ULONG *ckpLength);
+ * CK_VOID_PTR jMechParamToCKMechParamPtr(JNIEnv *env,
+ *                              jobject jParam,
+ *                              CK_MECHANISM_TYPE ckMech,
+ *                              CK_ULONG *ckpLength);
  *
  * These functions are used if a PKCS#11 mechanism or attribute structure gets
  * convertet to a Java attribute or mechanism object or vice versa.
@@ -927,22 +1023,21 @@
  * be a CK_ULONG, CK_BYTE[], CK_CHAR[], big integer, CK_BBOOL, CK_UTF8CHAR[],
  * CK_DATE or CK_FLAGS that gets converted to a corresponding Java object.
  *
- * jObjectToPrimitiveCKObjectPtrPtr is used by jAttributeToCKAttributePtr for
+ * jObjectToPrimitiveCKObjectPtr is used by jAttributeToCKAttributePtr for
  * converting the Java attribute value to a PKCS#11 attribute value pointer.
  * For now only primitive datatypes and arrays of primitive datatypes can get
  * converted. Otherwise this function throws a PKCS#11Exception with the
  * errorcode CKR_VENDOR_DEFINED.
  *
- * jMechanismParameterToCKMechanismParameter converts a Java mechanism parameter
- * to a PKCS#11 mechanism parameter. First this function determines what mechanism
- * parameter the Java object is, then it allocates the memory for the new PKCS#11
- * structure and calls the corresponding function to convert the Java object to
- * a PKCS#11 mechanism parameter structure.
+ * jMechParamToCKMechParamPtr converts a Java mechanism parameter to a PKCS#11
+ * mechanism parameter. Based on the specified PKCS#11 mechanism type, this
+ * function will allocate memory for a PKCS#11 parameter structure and
+ * populate its field using the Java object.
  */
 
 /*
- * converts the pValue of a CK_ATTRIBUTE structure into a Java Object by checking the type
- * of the attribute.
+ * converts the pValue of a CK_ATTRIBUTE structure into a Java Object by
+ * checking the type of the attribute.
  *
  * @param env - used to call JNI funktions to create the new Java object
  * @param ckpAttribute - the pointer to the CK_ATTRIBUTE structure that contains the type
@@ -1096,474 +1191,283 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java mechanism parameter object to convert
- * @param ckpParamPtr - the reference of the new pointer to the new CK mechanism parameter
- *                      structure
+ * @param ckMech - the PKCS#11 mechanism type
  * @param ckpLength - the reference of the length in bytes of the new CK mechanism parameter
  *                    structure
+ * @return pointer to the new CK mechanism parameter structure
  */
-void jMechanismParameterToCKMechanismParameter(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength)
+CK_VOID_PTR jMechParamToCKMechParamPtr(JNIEnv *env, jobject jParam,
+        CK_MECHANISM_TYPE ckMech, CK_ULONG *ckpLength)
 {
+    CK_VOID_PTR ckpParamPtr;
     if (jParam == NULL) {
-        *ckpParamPtr = NULL;
+        ckpParamPtr = NULL;
         *ckpLength = 0;
     } else if ((*env)->IsInstanceOf(env, jParam, jByteArrayClass)) {
-        jByteArrayToCKByteArray(env, jParam, (CK_BYTE_PTR *)ckpParamPtr, ckpLength);
+        jByteArrayToCKByteArray(env, jParam, (CK_BYTE_PTR *) &ckpParamPtr, ckpLength);
     } else if ((*env)->IsInstanceOf(env, jParam, jLongClass)) {
-        *ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
+        ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
         *ckpLength = sizeof(CK_ULONG);
     } else {
-        TRACE0("\nSLOW PATH jMechanismParameterToCKMechanismParameter\n");
-        jMechanismParameterToCKMechanismParameterSlow(env, jParam, ckpParamPtr, ckpLength);
+        ckpParamPtr = jMechParamToCKMechParamPtrSlow(env, jParam, ckMech, ckpLength);
     }
+    return ckpParamPtr;
 }
 
-void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength)
+CK_VOID_PTR jMechParamToCKMechParamPtrSlow(JNIEnv *env, jobject jParam,
+        CK_MECHANISM_TYPE ckMech, CK_ULONG *ckpLength)
 {
-    /* get all Java mechanism parameter classes */
-    jclass jVersionClass, jSsl3MasterKeyDeriveParamsClass;
-    jclass jTls12MasterKeyDeriveParamsClass, jSsl3KeyMatParamsClass;
-    jclass jTls12KeyMatParamsClass;
-    jclass jTlsPrfParamsClass, jTlsMacParamsClass, jAesCtrParamsClass;
-    jclass jRsaPkcsOaepParamsClass;
-    jclass jPbeParamsClass, jPkcs5Pbkd2ParamsClass, jRsaPkcsPssParamsClass;
-    jclass jEcdh1DeriveParamsClass, jEcdh2DeriveParamsClass;
-    jclass jX942Dh1DeriveParamsClass, jX942Dh2DeriveParamsClass;
-    TRACE0("\nDEBUG: jMechanismParameterToCKMechanismParameter");
+    CK_VOID_PTR ckpParamPtr = NULL;
 
-    /* most common cases, i.e. NULL/byte[]/long, are already handled by
-     * jMechanismParameterToCKMechanismParameter before calling this method.
+    /*
+     * Most common cases, i.e. NULL/byte[]/long, are already handled by
+     * jMechParamToCKMechParam before calling this method.
      */
-    jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
-    if (jVersionClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jVersionClass)) {
-        /*
-         * CK_VERSION used by CKM_SSL3_PRE_MASTER_KEY_GEN
-         */
-        CK_VERSION_PTR ckpParam;
+    TRACE1("\nDEBUG: jMechParamToCKMechParamPtrSlow, mech=0x%lX", ckMech);
 
-        /* convert jParameter to CKParameter */
-        ckpParam = jVersionToCKVersionPtr(env, jParam);
+    switch (ckMech) {
+        case CKM_SSL3_PRE_MASTER_KEY_GEN:
+        case CKM_TLS_PRE_MASTER_KEY_GEN:
+            *ckpLength = sizeof(CK_VERSION);
+            ckpParamPtr = jVersionToCKVersionPtr(env, jParam);
+            break;
+        case CKM_SSL3_MASTER_KEY_DERIVE:
+        case CKM_TLS_MASTER_KEY_DERIVE:
+        case CKM_SSL3_MASTER_KEY_DERIVE_DH:
+        case CKM_TLS_MASTER_KEY_DERIVE_DH:
+            ckpParamPtr =
+                    malloc(sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
 
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_VERSION);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
+            jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(env, jParam,
+                    (CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_SSL3_KEY_AND_MAC_DERIVE:
+        case CKM_TLS_KEY_AND_MAC_DERIVE:
+            ckpParamPtr =
+                    malloc(sizeof(CK_SSL3_KEY_MAT_PARAMS));
+            if (ckpParamPtr == NULL) {
+                 throwOutOfMemoryError(env, 0);
+                 return NULL;
+            }
+            *ckpLength = sizeof(CK_SSL3_KEY_MAT_PARAMS);
 
-    jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jSsl3MasterKeyDeriveParamsClass)) {
-        /*
-         * CK_SSL3_MASTER_KEY_DERIVE_PARAMS
-         */
-        CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR) malloc(sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
+            jSsl3KeyMatParamToCKSsl3KeyMatParam(env, jParam,
+                    (CK_SSL3_KEY_MAT_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_TLS12_KEY_AND_MAC_DERIVE:
+            ckpParamPtr =
+                    malloc(sizeof(CK_TLS12_KEY_MAT_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_TLS12_KEY_MAT_PARAMS);
 
-        /* convert jParameter to CKParameter */
-        *ckpParam = jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
+            jTls12KeyMatParamToCKTls12KeyMatParam(env, jParam,
+                    (CK_TLS12_KEY_MAT_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_TLS12_MASTER_KEY_DERIVE:
+        case CKM_TLS12_MASTER_KEY_DERIVE_DH:
+            ckpParamPtr =
+                    malloc(sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
 
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
-    if (jSsl3KeyMatParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jSsl3KeyMatParamsClass)) {
-        /*
-         * CK_SSL3_KEY_MAT_PARAMS
-         */
-        CK_SSL3_KEY_MAT_PARAMS_PTR ckpParam;
+            jTls12MasterKeyDeriveParamToCKTls12MasterKeyDeriveParam(env, jParam,
+                    (CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_TLS_PRF:
+        case CKM_NSS_TLS_PRF_GENERAL:
+            ckpParamPtr = malloc(sizeof(CK_TLS_PRF_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_TLS_PRF_PARAMS);
 
-        ckpParam = (CK_SSL3_KEY_MAT_PARAMS_PTR) malloc(sizeof(CK_SSL3_KEY_MAT_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jSsl3KeyMatParamToCKSsl3KeyMatParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
+            jTlsPrfParamsToCKTlsPrfParam(env, jParam,
+                    (CK_TLS_PRF_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_TLS_MAC:
+            ckpParamPtr = malloc(sizeof(CK_TLS_MAC_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_TLS_MAC_PARAMS);
 
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_SSL3_KEY_MAT_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
+            jTlsMacParamsToCKTlsMacParam(env, jParam,
+                    (CK_TLS_MAC_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_AES_CTR:
+            ckpParamPtr = malloc(sizeof(CK_AES_CTR_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_AES_CTR_PARAMS);
 
-    jTls12KeyMatParamsClass = (*env)->FindClass(env, CLASS_TLS12_KEY_MAT_PARAMS);
-    if (jTls12KeyMatParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jTls12KeyMatParamsClass)) {
-        /*
-         * CK_TLS12_KEY_MAT_PARAMS
-         */
-        CK_TLS12_KEY_MAT_PARAMS_PTR ckpParam;
+            jAesCtrParamsToCKAesCtrParam(env, jParam,
+                    (CK_AES_CTR_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_AES_GCM:
+            ckpParamPtr = malloc(sizeof(CK_GCM_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_GCM_PARAMS);
+
+            jGCMParamsToCKGCMParam(env, jParam, (CK_GCM_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_AES_CCM:
+            ckpParamPtr = malloc(sizeof(CK_CCM_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_CCM_PARAMS);
 
-        ckpParam = (CK_TLS12_KEY_MAT_PARAMS_PTR) malloc(sizeof(CK_TLS12_KEY_MAT_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
+            jCCMParamsToCKCCMParam(env, jParam,
+                    (CK_CCM_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_RSA_PKCS_OAEP:
+            ckpParamPtr = malloc(sizeof(CK_RSA_PKCS_OAEP_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_RSA_PKCS_OAEP_PARAMS);
 
-        /* convert jParameter to CKParameter */
-        *ckpParam = jTls12KeyMatParamToCKTls12KeyMatParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
+            jRsaPkcsOaepParamToCKRsaPkcsOaepParam(env, jParam,
+                    (CK_RSA_PKCS_OAEP_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_PBE_SHA1_DES3_EDE_CBC:
+        case CKM_PBE_SHA1_DES2_EDE_CBC:
+        case CKM_PBA_SHA1_WITH_SHA1_HMAC:
+            ckpParamPtr = malloc(sizeof(CK_PBE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
 
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_TLS12_KEY_MAT_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
+            *ckpLength = sizeof(CK_PBE_PARAMS);
 
-    jTls12MasterKeyDeriveParamsClass =
-            (*env)->FindClass(env, CLASS_TLS12_MASTER_KEY_DERIVE_PARAMS);
-    if (jTls12MasterKeyDeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jTls12MasterKeyDeriveParamsClass)) {
-        /*
-         * CK_TLS12_MASTER_KEY_DERIVE_PARAMS
-         */
-        CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR ckpParam;
+            jPbeParamToCKPbeParam(env, jParam, (CK_PBE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_PKCS5_PBKD2:
+            ckpParamPtr = malloc(sizeof(CK_PKCS5_PBKD2_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_PKCS5_PBKD2_PARAMS);
 
-        ckpParam = (CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR)malloc(
-                sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
+            jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(env, jParam,
+                     (CK_PKCS5_PBKD2_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_RSA_PKCS_PSS:
+        case CKM_SHA1_RSA_PKCS_PSS:
+        case CKM_SHA256_RSA_PKCS_PSS:
+        case CKM_SHA384_RSA_PKCS_PSS:
+        case CKM_SHA512_RSA_PKCS_PSS:
+        case CKM_SHA224_RSA_PKCS_PSS:
+            ckpParamPtr = malloc(sizeof(CK_RSA_PKCS_PSS_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_RSA_PKCS_PSS_PARAMS);
 
-        /* convert jParameter to CKParameter */
-        *ckpParam = jTls12MasterKeyDeriveParamToCKTls12MasterKeyDeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
+            jRsaPkcsPssParamToCKRsaPkcsPssParam(env, jParam,
+                    (CK_RSA_PKCS_PSS_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_ECDH1_DERIVE:
+        case CKM_ECDH1_COFACTOR_DERIVE:
+            ckpParamPtr = malloc(sizeof(CK_ECDH1_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_ECDH1_DERIVE_PARAMS);
 
-    jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
-    if (jTlsPrfParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jTlsPrfParamsClass)) {
-        /*
-         * CK_TLS_PRF_PARAMS
-         */
-        CK_TLS_PRF_PARAMS_PTR ckpParam;
+            jEcdh1DeriveParamToCKEcdh1DeriveParam(env, jParam,
+                    (CK_ECDH1_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_ECMQV_DERIVE:
+            ckpParamPtr = malloc(sizeof(CK_ECDH2_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_ECDH2_DERIVE_PARAMS);
 
-        ckpParam = (CK_TLS_PRF_PARAMS_PTR) malloc(sizeof(CK_TLS_PRF_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jTlsPrfParamsToCKTlsPrfParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
+            jEcdh2DeriveParamToCKEcdh2DeriveParam(env, jParam,
+                    (CK_ECDH2_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_X9_42_DH_DERIVE:
+            ckpParamPtr = malloc(sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_X9_42_DH1_DERIVE_PARAMS);
 
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_TLS_PRF_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jTlsMacParamsClass = (*env)->FindClass(env, CLASS_TLS_MAC_PARAMS);
-    if (jTlsMacParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jTlsMacParamsClass)) {
-        CK_TLS_MAC_PARAMS_PTR ckpParam;
+            /* convert jParameter to CKParameter */
+            jX942Dh1DeriveParamToCKX942Dh1DeriveParam(env, jParam,
+                (CK_X9_42_DH1_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        case CKM_X9_42_DH_HYBRID_DERIVE:
+        case CKM_X9_42_MQV_DERIVE:
+            ckpParamPtr = malloc(sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
+            if (ckpParamPtr == NULL) {
+                throwOutOfMemoryError(env, 0);
+                return NULL;
+            }
+            *ckpLength = sizeof(CK_X9_42_DH2_DERIVE_PARAMS);
 
-        ckpParam = (CK_TLS_MAC_PARAMS_PTR) malloc(sizeof(CK_TLS_MAC_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
+            jX942Dh2DeriveParamToCKX942Dh2DeriveParam(env, jParam,
+                    (CK_X9_42_DH2_DERIVE_PARAMS_PTR) ckpParamPtr);
+            break;
+        // defined by pkcs11.h but we don't support
+        case CKM_KEA_DERIVE: // CK_KEA_DERIVE_PARAMS
+        case CKM_RC2_CBC: // CK_RC2_CBC_PARAMS
+        case CKM_RC2_MAC_GENERAL: // CK_RC2_MAC_GENERAL_PARAMS
+        case CKM_RC5_ECB: // CK_RC5_PARAMS
+        case CKM_RC5_MAC: // CK_RC5_PARAMS
+        case CKM_RC5_CBC: // CK_RC5_CBC_PARAMS
+        case CKM_RC5_MAC_GENERAL: // CK_RC5_MAC_GENERAL_PARAMS
+        case CKM_SKIPJACK_PRIVATE_WRAP: // CK_SKIPJACK_PRIVATE_WRAP_PARAMS
+        case CKM_SKIPJACK_RELAYX: // CK_SKIPJACK_RELAYX_PARAMS
+        case CKM_KEY_WRAP_SET_OAEP: // CK_KEY_WRAP_SET_OAEP_PARAMS
+            throwPKCS11RuntimeException(env, "No parameter support for this mchanism");
+            break;
+        default:
+            /* if everything faild up to here */
+            /* try if the parameter is a primitive Java type */
+            ckpParamPtr = jObjectToPrimitiveCKObjectPtr(env, jParam, ckpLength);
+            /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
+            /* *ckpLength = 1; */
+    }
+    TRACE0("\nDEBUG: jMechParamToCKMechParamPtrSlow FINISHED\n");
 
-        /* convert jParameter to CKParameter */
-        *ckpParam = jTlsMacParamsToCKTlsMacParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_TLS_MAC_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpParamPtr);
+        *ckpLength = 0;
+        return NULL;
     }
 
-    jAesCtrParamsClass = (*env)->FindClass(env, CLASS_AES_CTR_PARAMS);
-    if (jAesCtrParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jAesCtrParamsClass)) {
-        /*
-         * CK_AES_CTR_PARAMS
-         */
-        CK_AES_CTR_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_AES_CTR_PARAMS_PTR) malloc(sizeof(CK_AES_CTR_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        jAesCtrParamsToCKAesCtrParam(env, jParam, ckpParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_AES_CTR_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
-    if (jRsaPkcsOaepParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
-        /*
-         * CK_RSA_PKCS_OAEP_PARAMS
-         */
-        CK_RSA_PKCS_OAEP_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_RSA_PKCS_OAEP_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_OAEP_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jRsaPkcsOaepParamToCKRsaPkcsOaepParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_RSA_PKCS_OAEP_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
-    if (jPbeParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jPbeParamsClass)) {
-        /*
-         * CK_PBE_PARAMS
-         */
-        CK_PBE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_PBE_PARAMS_PTR) malloc(sizeof(CK_PBE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jPbeParamToCKPbeParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_PBE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
-    if (jPkcs5Pbkd2ParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jPkcs5Pbkd2ParamsClass)) {
-        /*
-         * CK_PKCS5_PBKD2_PARAMS
-         */
-        CK_PKCS5_PBKD2_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_PKCS5_PBKD2_PARAMS_PTR) malloc(sizeof(CK_PKCS5_PBKD2_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_PKCS5_PBKD2_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
-    if (jRsaPkcsPssParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsPssParamsClass)) {
-        /*
-         * CK_RSA_PKCS_PSS_PARAMS
-         */
-        CK_RSA_PKCS_PSS_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_RSA_PKCS_PSS_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_PSS_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jRsaPkcsPssParamToCKRsaPkcsPssParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_RSA_PKCS_PSS_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
-    if (jEcdh1DeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jEcdh1DeriveParamsClass)) {
-        /*
-         * CK_ECDH1_DERIVE_PARAMS
-         */
-        CK_ECDH1_DERIVE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_ECDH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH1_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jEcdh1DeriveParamToCKEcdh1DeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_ECDH1_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
-    if (jEcdh2DeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jEcdh2DeriveParamsClass)) {
-        /*
-         * CK_ECDH2_DERIVE_PARAMS
-         */
-        CK_ECDH2_DERIVE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_ECDH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH2_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jEcdh2DeriveParamToCKEcdh2DeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_ECDH2_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
-    if (jX942Dh1DeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jX942Dh1DeriveParamsClass)) {
-        /*
-         * CK_X9_42_DH1_DERIVE_PARAMS
-         */
-        CK_X9_42_DH1_DERIVE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_X9_42_DH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jX942Dh1DeriveParamToCKX942Dh1DeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_X9_42_DH1_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
-    if (jX942Dh2DeriveParamsClass == NULL) { return; }
-    if ((*env)->IsInstanceOf(env, jParam, jX942Dh2DeriveParamsClass)) {
-        /*
-         * CK_X9_42_DH2_DERIVE_PARAMS
-         */
-        CK_X9_42_DH2_DERIVE_PARAMS_PTR ckpParam;
-
-        ckpParam = (CK_X9_42_DH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
-        if (ckpParam == NULL) {
-            throwOutOfMemoryError(env, 0);
-            return;
-        }
-
-        /* convert jParameter to CKParameter */
-        *ckpParam = jX942Dh2DeriveParamToCKX942Dh2DeriveParam(env, jParam);
-        if ((*env)->ExceptionCheck(env)) {
-            free(ckpParam);
-            return;
-        }
-
-        /* get length and pointer of parameter */
-        *ckpLength = sizeof(CK_X9_42_DH2_DERIVE_PARAMS);
-        *ckpParamPtr = ckpParam;
-        return;
-    }
-
-    /* if everything faild up to here */
-    /* try if the parameter is a primitive Java type */
-    jObjectToPrimitiveCKObjectPtrPtr(env, jParam, ckpParamPtr, ckpLength);
-    /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
-    /* *ckpLength = 1; */
-
-    TRACE0("FINISHED\n");
+    return ckpParamPtr;
 }
 
-
 /* the mechanism parameter convertion functions: */
 
 /*
@@ -1573,47 +1477,45 @@
  * @param jParam - the Java CK_RSA_PKCS_OAEP_PARAMS object to convert
  * @return - the new CK_RSA_PKCS_OAEP_PARAMS structure
  */
-CK_RSA_PKCS_OAEP_PARAMS jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam)
+void jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam,
+CK_RSA_PKCS_OAEP_PARAMS_PTR ckParamPtr)
 {
     jclass jRsaPkcsOaepParamsClass;
-    CK_RSA_PKCS_OAEP_PARAMS ckParam;
     jfieldID fieldID;
     jlong jHashAlg, jMgf, jSource;
     jobject jSourceData;
     CK_BYTE_PTR ckpByte;
-    memset(&ckParam, 0, sizeof(CK_RSA_PKCS_OAEP_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_RSA_PKCS_OAEP_PARAMS));
 
     /* get hashAlg */
     jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
-    if (jRsaPkcsOaepParamsClass == NULL) { return ckParam; }
+    if (jRsaPkcsOaepParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "hashAlg", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "mgf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get source */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "source", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sourceData and sourceDataLength */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "pSourceData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSourceData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.hashAlg = jLongToCKULong(jHashAlg);
-    ckParam.mgf = jLongToCKULong(jMgf);
-    ckParam.source = jLongToCKULong(jSource);
-    jByteArrayToCKByteArray(env, jSourceData, & ckpByte, &(ckParam.ulSourceDataLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    ckParam.pSourceData = (CK_VOID_PTR) ckpByte;
-
-    return ckParam ;
+    ckParamPtr->hashAlg = jLongToCKULong(jHashAlg);
+    ckParamPtr->mgf = jLongToCKULong(jMgf);
+    ckParamPtr->source = jLongToCKULong(jSource);
+    jByteArrayToCKByteArray(env, jSourceData, & ckpByte, &(ckParamPtr->ulSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    ckParamPtr->pSourceData = (CK_VOID_PTR) ckpByte;
 }
 
 /*
@@ -1621,57 +1523,55 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_PBE_PARAMS object to convert
- * @return - the new CK_PBE_PARAMS structure
+ * @param ckParamPtr pointer to the new CK_PBE_PARAMS structure
  */
-CK_PBE_PARAMS jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam)
+void jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam,
+CK_PBE_PARAMS_PTR ckParamPtr)
 {
     jclass jPbeParamsClass;
-    CK_PBE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jIteration;
     jobject jInitVector, jPassword, jSalt;
     CK_ULONG ckTemp;
-    memset(&ckParam, 0, sizeof(CK_PBE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_PBE_PARAMS));
 
     /* get pInitVector */
     jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
-    if (jPbeParamsClass == NULL) { return ckParam; }
+    if (jPbeParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pInitVector", "[C");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jInitVector = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPassword and ulPasswordLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pPassword", "[C");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPassword = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pSalt and ulSaltLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pSalt", "[C");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSalt = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulIteration */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "ulIteration", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jIteration = (*env)->GetLongField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.ulIteration = jLongToCKULong(jIteration);
-    jCharArrayToCKCharArray(env, jInitVector, &(ckParam.pInitVector), &ckTemp);
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jCharArrayToCKCharArray(env, jPassword, &(ckParam.pPassword), &(ckParam.ulPasswordLen));
+    ckParamPtr->ulIteration = jLongToCKULong(jIteration);
+    jCharArrayToCKCharArray(env, jInitVector, &(ckParamPtr->pInitVector), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jCharArrayToCKCharArray(env, jPassword, &(ckParamPtr->pPassword), &(ckParamPtr->ulPasswordLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pInitVector);
-        return ckParam;
+        free(ckParamPtr->pInitVector);
+        return;
     }
-    jCharArrayToCKCharArray(env, jSalt, &(ckParam.pSalt), &(ckParam.ulSaltLen));
+    jCharArrayToCKCharArray(env, jSalt, &(ckParamPtr->pSalt), &(ckParamPtr->ulSaltLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pInitVector);
-        free(ckParam.pPassword);
-        return ckParam;
+        free(ckParamPtr->pInitVector);
+        free(ckParamPtr->pPassword);
+        return;
     }
-
-    return ckParam ;
 }
 
 /*
@@ -1741,57 +1641,55 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_PKCS5_PBKD2_PARAMS object to convert
- * @return - the new CK_PKCS5_PBKD2_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_PKCS5_PBKD2_PARAMS structure
  */
-CK_PKCS5_PBKD2_PARAMS jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam)
+void jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam,
+CK_PKCS5_PBKD2_PARAMS_PTR ckParamPtr)
 {
     jclass jPkcs5Pbkd2ParamsClass;
-    CK_PKCS5_PBKD2_PARAMS ckParam;
     jfieldID fieldID;
     jlong jSaltSource, jIteration, jPrf;
     jobject jSaltSourceData, jPrfData;
-    memset(&ckParam, 0, sizeof(CK_PKCS5_PBKD2_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_PKCS5_PBKD2_PARAMS));
 
     /* get saltSource */
     jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
-    if (jPkcs5Pbkd2ParamsClass == NULL) { return ckParam; }
+    if (jPkcs5Pbkd2ParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "saltSource", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSaltSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSaltSourceData */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pSaltSourceData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSaltSourceData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get iterations */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "iterations", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jIteration = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get prf */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "prf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPrfData and ulPrfDataLength in byte */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pPrfData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrfData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.saltSource = jLongToCKULong(jSaltSource);
-    jByteArrayToCKByteArray(env, jSaltSourceData, (CK_BYTE_PTR *) &(ckParam.pSaltSourceData), &(ckParam.ulSaltSourceDataLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    ckParam.iterations = jLongToCKULong(jIteration);
-    ckParam.prf = jLongToCKULong(jPrf);
-    jByteArrayToCKByteArray(env, jPrfData, (CK_BYTE_PTR *) &(ckParam.pPrfData), &(ckParam.ulPrfDataLen));
+    ckParamPtr->saltSource = jLongToCKULong(jSaltSource);
+    jByteArrayToCKByteArray(env, jSaltSourceData, (CK_BYTE_PTR *) &(ckParamPtr->pSaltSourceData), &(ckParamPtr->ulSaltSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    ckParamPtr->iterations = jLongToCKULong(jIteration);
+    ckParamPtr->prf = jLongToCKULong(jPrf);
+    jByteArrayToCKByteArray(env, jPrfData, (CK_BYTE_PTR *) &(ckParamPtr->pPrfData), &(ckParamPtr->ulPrfDataLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSaltSourceData);
-        return ckParam;
+        free(ckParamPtr->pSaltSourceData);
+        return;
     }
-
-    return ckParam ;
 }
 
 /*
@@ -1799,39 +1697,40 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_RSA_PKCS_PSS_PARAMS object to convert
- * @return - the new CK_RSA_PKCS_PSS_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_RSA_PKCS_PSS_PARAMS structure
  */
-CK_RSA_PKCS_PSS_PARAMS jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam)
+void jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam,
+CK_RSA_PKCS_PSS_PARAMS_PTR ckParamPtr)
 {
     jclass jRsaPkcsPssParamsClass;
-    CK_RSA_PKCS_PSS_PARAMS ckParam;
     jfieldID fieldID;
     jlong jHashAlg, jMgf, jSLen;
-    memset(&ckParam, 0, sizeof(CK_RSA_PKCS_PSS_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_RSA_PKCS_PSS_PARAMS));
 
     /* get hashAlg */
     jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
-    if (jRsaPkcsPssParamsClass == NULL) { return ckParam; }
+    if (jRsaPkcsPssParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "hashAlg", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "mgf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sLen */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "sLen", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.hashAlg = jLongToCKULong(jHashAlg);
-    ckParam.mgf = jLongToCKULong(jMgf);
-    ckParam.sLen = jLongToCKULong(jSLen);
-
-    return ckParam ;
+    ckParamPtr->hashAlg = jLongToCKULong(jHashAlg);
+    ckParamPtr->mgf = jLongToCKULong(jMgf);
+    ckParamPtr->sLen = jLongToCKULong(jSLen);
+    TRACE1("DEBUG: jRsaPkcsPssParamToCKRsaPkcsPssParam, hashAlg=0x%lX\n", ckParamPtr->hashAlg);
+    TRACE1("DEBUG: jRsaPkcsPssParamToCKRsaPkcsPssParam, mgf=0x%lX\n", ckParamPtr->mgf);
+    TRACE1("DEBUG: jRsaPkcsPssParamToCKRsaPkcsPssParam, sLen=%lu\n", ckParamPtr->sLen);
 }
 
 /*
@@ -1839,46 +1738,44 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_ECDH1_DERIVE_PARAMS object to convert
- * @return - the new CK_ECDH1_DERIVE_PARAMS structure
+ * @param ckParamPtr - the new CK_ECDH1_DERIVE_PARAMS structure
  */
-CK_ECDH1_DERIVE_PARAMS jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam)
+void jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam,
+CK_ECDH1_DERIVE_PARAMS_PTR ckParamPtr)
 {
     jclass jEcdh1DeriveParamsClass;
-    CK_ECDH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jLong;
     jobject jSharedData, jPublicData;
-    memset(&ckParam, 0, sizeof(CK_ECDH1_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_ECDH1_DERIVE_PARAMS));
 
     /* get kdf */
     jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
-    if (jEcdh1DeriveParamsClass == NULL) { return ckParam; }
+    if (jEcdh1DeriveParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "kdf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    ckParamPtr->kdf = jLongToCKULong(jLong);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pSharedData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pPublicData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.kdf = jLongToCKULong(jLong);
-    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    ckParamPtr->kdf = jLongToCKULong(jLong);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParamPtr->pSharedData), &(ckParamPtr->ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParamPtr->pPublicData), &(ckParamPtr->ulPublicDataLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSharedData);
-        return ckParam;
+        free(ckParamPtr->pSharedData);
+        return;
     }
-
-    return ckParam ;
 }
 
 /*
@@ -1886,67 +1783,66 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_ECDH2_DERIVE_PARAMS object to convert
- * @return - the new CK_ECDH2_DERIVE_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_ECDH2_DERIVE_PARAMS structure
  */
-CK_ECDH2_DERIVE_PARAMS jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam)
+void jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam,
+CK_ECDH2_DERIVE_PARAMS_PTR ckParamPtr)
 {
     jclass jEcdh2DeriveParamsClass;
-    CK_ECDH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jKdf, jPrivateDataLen, jPrivateData;
     jobject jSharedData, jPublicData, jPublicData2;
-    memset(&ckParam, 0, sizeof(CK_ECDH2_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_ECDH2_DERIVE_PARAMS));
 
     /* get kdf */
     jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
-    if (jEcdh2DeriveParamsClass == NULL) { return ckParam; }
+    if (jEcdh2DeriveParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "kdf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pSharedData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "hPrivateData", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData2", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.kdf = jLongToCKULong(jKdf);
-    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    ckParamPtr->kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParamPtr->pSharedData), &(ckParamPtr->ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParamPtr->pPublicData), &(ckParamPtr->ulPublicDataLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSharedData);
-        return ckParam;
+        free(ckParamPtr->pSharedData);
+        return;
     }
-    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
-    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
-    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    ckParamPtr->ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParamPtr->hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParamPtr->pPublicData2), &(ckParamPtr->ulPublicDataLen2));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pSharedData);
-        free(ckParam.pPublicData);
-        return ckParam;
+        free(ckParamPtr->pSharedData);
+        free(ckParamPtr->pPublicData);
+        return;
     }
-    return ckParam ;
 }
 
 /*
@@ -1954,45 +1850,43 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_X9_42_DH1_DERIVE_PARAMS object to convert
- * @return - the new CK_X9_42_DH1_DERIVE_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_X9_42_DH1_DERIVE_PARAMS structure
  */
-CK_X9_42_DH1_DERIVE_PARAMS jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam)
+void jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam,
+        CK_X9_42_DH1_DERIVE_PARAMS_PTR ckParamPtr)
 {
     jclass jX942Dh1DeriveParamsClass;
-    CK_X9_42_DH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jKdf;
     jobject jOtherInfo, jPublicData;
-    memset(&ckParam, 0, sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
 
     /* get kdf */
     jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
-    if (jX942Dh1DeriveParamsClass == NULL) { return ckParam; }
+    if (jX942Dh1DeriveParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "kdf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pOtherInfo", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pPublicData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.kdf = jLongToCKULong(jKdf);
-    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    ckParamPtr->kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParamPtr->pOtherInfo), &(ckParamPtr->ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParamPtr->pPublicData), &(ckParamPtr->ulPublicDataLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pOtherInfo);
-        return ckParam;
+        free(ckParamPtr->pOtherInfo);
+        return;
     }
-
-    return ckParam ;
 }
 
 /*
@@ -2000,66 +1894,64 @@
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jParam - the Java CK_X9_42_DH2_DERIVE_PARAMS object to convert
- * @return - the new CK_X9_42_DH2_DERIVE_PARAMS structure
+ * @param ckParamPtr - pointer to the new CK_X9_42_DH2_DERIVE_PARAMS structure
  */
-CK_X9_42_DH2_DERIVE_PARAMS jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam)
+void jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam,
+        CK_X9_42_DH2_DERIVE_PARAMS_PTR ckParamPtr)
 {
     jclass jX942Dh2DeriveParamsClass;
-    CK_X9_42_DH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jKdf, jPrivateDataLen, jPrivateData;
     jobject jOtherInfo, jPublicData, jPublicData2;
-    memset(&ckParam, 0, sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
+    memset(ckParamPtr, 0, sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
 
     /* get kdf */
     jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
-    if (jX942Dh2DeriveParamsClass == NULL) { return ckParam; }
+    if (jX942Dh2DeriveParamsClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "kdf", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pOtherInfo", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "hPrivateData", "J");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData2", "[B");
-    if (fieldID == NULL) { return ckParam; }
+    if (fieldID == NULL) { return; }
     jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* populate java values */
-    ckParam.kdf = jLongToCKULong(jKdf);
-    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
-    if ((*env)->ExceptionCheck(env)) { return ckParam; }
-    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    ckParamPtr->kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParamPtr->pOtherInfo), &(ckParamPtr->ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParamPtr->pPublicData), &(ckParamPtr->ulPublicDataLen));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pOtherInfo);
-        return ckParam;
+        free(ckParamPtr->pOtherInfo);
+        return;
     }
-    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
-    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
-    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    ckParamPtr->ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParamPtr->hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParamPtr->pPublicData2), &(ckParamPtr->ulPublicDataLen2));
     if ((*env)->ExceptionCheck(env)) {
-        free(ckParam.pOtherInfo);
-        free(ckParam.pPublicData);
-        return ckParam;
+        free(ckParamPtr->pOtherInfo);
+        free(ckParamPtr->pPublicData);
+        return;
     }
-
-    return ckParam ;
 }
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_crypt.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_crypt.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -71,7 +71,7 @@
  jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
@@ -80,15 +80,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
 
-    rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, &ckMechanism,
+    rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, ckpMechanism,
                                         ckKeyHandle);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+    // if OAEP, then cannot free here
+    freeCKMechanismPtr(ckpMechanism);
 
     if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
@@ -98,54 +97,67 @@
 /*
  * Class:     sun_security_pkcs11_wrapper_PKCS11
  * Method:    C_Encrypt
- * Signature: (J[BII[BII)I
+ * Signature: (JJ[BIIJ[BII)I
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
+ * @param   jlong directIn              CK_BYTE_PTR pData
  * @param   jbyteArray jData            CK_BYTE_PTR pData
  *                                      CK_ULONG ulDataLen
- * @return  jbyteArray jEncryptedData   CK_BYTE_PTR pEncryptedData
+ * @param   jlong directOut             CK_BYTE_PTR pEncryptedData
+ * @return  jint encryptedDataLen       CK_BYTE_PTR pEncryptedData
  *                                      CK_ULONG_PTR pulEncryptedDataLen
  */
 JNIEXPORT jint JNICALL
 Java_sun_security_pkcs11_wrapper_PKCS11_C_1Encrypt
 (JNIEnv *env, jobject obj, jlong jSessionHandle,
- jbyteArray jIn, jint jInOfs, jint jInLen,
- jbyteArray jOut, jint jOutOfs, jint jOutLen)
+ jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen,
+ jlong directOut, jbyteArray jOut, jint jOutOfs, jint jOutLen)
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_RV rv;
 
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP;
-    CK_ULONG ckEncryptedPartLen;
+    CK_ULONG ckEncryptedLen = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
-    inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
-    if (inBufP == NULL) { return 0; }
-
-    outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
-    if (outBufP == NULL) {
-        // Make sure to release inBufP
-        (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-        return 0;
+    if (directIn != 0) {
+      inBufP = (CK_BYTE_PTR) jlong_to_ptr(directIn);
+    } else {
+      inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
+      if (inBufP == NULL) { return 0; }
     }
 
-    ckEncryptedPartLen = jOutLen;
+    if (directOut != 0) {
+      outBufP = (CK_BYTE_PTR) jlong_to_ptr(directOut);
+    } else {
+      outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
+      if (outBufP == NULL) {
+          goto cleanup;
+      }
+    }
+
+    ckEncryptedLen = jOutLen;
 
     rv = (*ckpFunctions->C_Encrypt)(ckSessionHandle,
                                     (CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
                                     (CK_BYTE_PTR)(outBufP + jOutOfs),
-                                    &ckEncryptedPartLen);
-
-    (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-    (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
+                                    &ckEncryptedLen);
 
     ckAssertReturnValueOK(env, rv);
-    return ckEncryptedPartLen;
+
+cleanup:
+    if (directIn == 0 && inBufP != NULL) {
+        (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
+    }
+    if (directOut == 0 && outBufP != NULL) {
+        (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
+    }
+    return ckEncryptedLen;
 }
 #endif
 
@@ -172,7 +184,7 @@
 
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP;
-    CK_ULONG ckEncryptedPartLen;
+    CK_ULONG ckEncryptedPartLen = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
@@ -191,34 +203,26 @@
     } else {
       outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
       if (outBufP == NULL) {
-          // Make sure to release inBufP
-          (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-          return 0;
+          goto cleanup;
       }
     }
 
     ckEncryptedPartLen = jOutLen;
 
-    //printf("EU: inBufP=%i, jInOfs=%i, jInLen=%i, outBufP=%i\n",
-    //       inBufP, jInOfs, jInLen, outBufP);
-
     rv = (*ckpFunctions->C_EncryptUpdate)(ckSessionHandle,
                                           (CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
                                           (CK_BYTE_PTR)(outBufP + jOutOfs),
                                           &ckEncryptedPartLen);
 
-    //printf("EU: ckEncryptedPartLen=%i\n", ckEncryptedPartLen);
+    ckAssertReturnValueOK(env, rv);
 
-    if (directIn == 0) {
+cleanup:
+    if (directIn == 0 && inBufP != NULL) {
         (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
     }
-
-    if (directOut == 0) {
+    if (directOut == 0 && outBufP != NULL) {
         (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
     }
-
-    ckAssertReturnValueOK(env, rv);
-
     return ckEncryptedPartLen;
 }
 #endif
@@ -257,14 +261,10 @@
 
     ckLastEncryptedPartLen = jOutLen;
 
-    //printf("EF: outBufP=%i\n", outBufP);
-
     rv = (*ckpFunctions->C_EncryptFinal)(ckSessionHandle,
                                          (CK_BYTE_PTR)(outBufP + jOutOfs),
                                          &ckLastEncryptedPartLen);
 
-    //printf("EF: ckLastEncryptedPartLen=%i", ckLastEncryptedPartLen);
-
     if (directOut == 0) {
         (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
     }
@@ -291,7 +291,7 @@
  jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
@@ -300,15 +300,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
 
-    rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, &ckMechanism,
+    rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, ckpMechanism,
                                         ckKeyHandle);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+    // if OAEP, then cannot free here
+    freeCKMechanismPtr(ckpMechanism);
 
     if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
@@ -318,7 +317,7 @@
 /*
  * Class:     sun_security_pkcs11_wrapper_PKCS11
  * Method:    C_Decrypt
- * Signature: (J[BII[BII)I
+ * Signature: (JJ[BIIJ[BII)I
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
  * @param   jbyteArray jEncryptedData   CK_BYTE_PTR pEncryptedData
@@ -329,44 +328,53 @@
 JNIEXPORT jint JNICALL
 Java_sun_security_pkcs11_wrapper_PKCS11_C_1Decrypt
 (JNIEnv *env, jobject obj, jlong jSessionHandle,
- jbyteArray jIn, jint jInOfs, jint jInLen,
- jbyteArray jOut, jint jOutOfs, jint jOutLen)
+ jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen,
+ jlong directOut, jbyteArray jOut, jint jOutOfs, jint jOutLen)
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_RV rv;
 
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP;
-    CK_ULONG ckPartLen;
+    CK_ULONG ckOutLen = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
-    inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
-    if (inBufP == NULL) { return 0; }
-
-    outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
-    if (outBufP == NULL) {
-        // Make sure to release inBufP
-        (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-        return 0;
+    if (directIn != 0) {
+      inBufP = (CK_BYTE_PTR) jlong_to_ptr(directIn);
+    } else {
+      inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
+      if (inBufP == NULL) { return 0; }
     }
 
-    ckPartLen = jOutLen;
+    if (directOut != 0) {
+      outBufP = (CK_BYTE_PTR) jlong_to_ptr(directOut);
+    } else {
+      outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
+      if (outBufP == NULL) {
+          goto cleanup;
+      }
+    }
+    ckOutLen = jOutLen;
 
     rv = (*ckpFunctions->C_Decrypt)(ckSessionHandle,
                                     (CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
                                     (CK_BYTE_PTR)(outBufP + jOutOfs),
-                                    &ckPartLen);
-
-    (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-    (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
+                                    &ckOutLen);
 
     ckAssertReturnValueOK(env, rv);
 
-    return ckPartLen;
+cleanup:
+    if (directIn == 0 && inBufP != NULL) {
+        (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
+    }
+    if (directOut == 0 && outBufP != NULL) {
+        (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
+    }
+    return ckOutLen;
 }
 #endif
 
@@ -393,7 +401,7 @@
 
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP;
-    CK_ULONG ckDecryptedPartLen;
+    CK_ULONG ckDecryptedPartLen = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
@@ -412,28 +420,24 @@
     } else {
       outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
       if (outBufP == NULL) {
-          // Make sure to release inBufP
-          (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
-          return 0;
+          goto cleanup;
       }
     }
 
     ckDecryptedPartLen = jOutLen;
-
     rv = (*ckpFunctions->C_DecryptUpdate)(ckSessionHandle,
                                           (CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
                                           (CK_BYTE_PTR)(outBufP + jOutOfs),
                                           &ckDecryptedPartLen);
-    if (directIn == 0) {
+    ckAssertReturnValueOK(env, rv);
+
+cleanup:
+    if (directIn == 0 && inBufP != NULL) {
         (*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
     }
-
-    if (directOut == 0) {
+    if (directOut == 0 && outBufP != NULL) {
         (*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
     }
-
-    ckAssertReturnValueOK(env, rv);
-
     return ckDecryptedPartLen;
 }
 
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_digest.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_digest.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -68,21 +68,19 @@
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
 
-    rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
+    rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, ckpMechanism);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+    freeCKMechanismPtr(ckpMechanism);
 
     if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
@@ -101,53 +99,50 @@
  *                                      CK_ULONG_PTR pulDigestLen
  */
 JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestSingle
-  (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jbyteArray jIn, jint jInOfs, jint jInLen, jbyteArray jDigest, jint jDigestOfs, jint jDigestLen)
+    (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism,
+     jbyteArray jIn, jint jInOfs, jint jInLen, jbyteArray jDigest,
+     jint jDigestOfs, jint jDigestLen)
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_RV rv;
-    CK_BYTE_PTR bufP;
     CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
+    CK_BYTE_PTR bufP = BUF;
     CK_BYTE DIGESTBUF[MAX_DIGEST_LEN];
-    CK_ULONG ckDigestLength = min(MAX_DIGEST_LEN, jDigestLen);
-    CK_MECHANISM ckMechanism;
+    CK_ULONG ckDigestLength = 0;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return 0; }
 
-    rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
-
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+    rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, ckpMechanism);
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { goto cleanup; }
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
-
-    if (jInLen <= MAX_STACK_BUFFER_LEN) {
-        bufP = BUF;
-    } else {
+    if (jInLen > MAX_STACK_BUFFER_LEN) {
         /* always use single part op, even for large data */
         bufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
         if (bufP == NULL) {
             throwOutOfMemoryError(env, 0);
-            return 0;
+            goto cleanup;
         }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)bufP);
     if ((*env)->ExceptionCheck(env)) {
-        if (bufP != BUF) { free(bufP); }
-        return 0;
+        goto cleanup;
     }
 
+    ckDigestLength = min(MAX_DIGEST_LEN, jDigestLen);
+
     rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
     }
-
+cleanup:
+    freeCKMechanismPtr(ckpMechanism);
     if (bufP != BUF) { free(bufP); }
 
     return ckDigestLength;
@@ -165,7 +160,8 @@
  *                                      CK_ULONG ulDataLen
  */
 JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestUpdate
-  (JNIEnv *env, jobject obj, jlong jSessionHandle, jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen)
+    (JNIEnv *env, jobject obj, jlong jSessionHandle, jlong directIn, jbyteArray jIn,
+     jint jInOfs, jint jInLen)
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_RV rv;
@@ -256,7 +252,8 @@
  *                                      CK_ULONG_PTR pulDigestLen
  */
 JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestFinal
-  (JNIEnv *env, jobject obj, jlong jSessionHandle, jbyteArray jDigest, jint jDigestOfs, jint jDigestLen)
+    (JNIEnv *env, jobject obj, jlong jSessionHandle, jbyteArray jDigest,
+     jint jDigestOfs, jint jDigestLen)
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_RV rv;
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_general.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_general.c	Wed Jun 12 10:02:49 2019 +0530
@@ -67,6 +67,7 @@
 jfieldID pNativeDataID;
 jfieldID mech_mechanismID;
 jfieldID mech_pParameterID;
+jfieldID mech_pHandleID;
 
 jclass jByteArrayClass;
 jclass jLongClass;
@@ -85,6 +86,23 @@
 /* ************************************************************************** */
 
 /*
+ * This method is used to do free the memory allocated for CK_MECHANISM structure.
+ *
+ * Class:     sun_security_pkcs11_wrapper_PKCS11
+ * Method:    freeMechanism
+ * Signature: (J)J
+ */
+JNIEXPORT jlong JNICALL
+Java_sun_security_pkcs11_wrapper_PKCS11_freeMechanism
+(JNIEnv *env, jclass thisClass, jlong ckpMechanism) {
+    if (ckpMechanism != 0L) {
+        freeCKMechanismPtr((CK_MECHANISM_PTR) ckpMechanism);
+        TRACE1("DEBUG PKCS11_freeMechanism: free pMech = %x\n", (jlong)ckpMechanism);
+    }
+    return 0L;
+}
+
+/*
  * This method is used to do static initialization. This method is static and
  * synchronized. Summary: use this method like a static initialization block.
  *
@@ -115,11 +133,11 @@
 void prefetchFields(JNIEnv *env, jclass thisClass) {
     jclass tmpClass;
 
-    /* PKCS11 */
+    /* PKCS11 - pNativeData */
     pNativeDataID = (*env)->GetFieldID(env, thisClass, "pNativeData", "J");
     if (pNativeDataID == NULL) { return; }
 
-    /* CK_MECHANISM */
+    /* CK_MECHANISM - mechanism, pParameter, pHandle */
     tmpClass = (*env)->FindClass(env, CLASS_MECHANISM);
     if (tmpClass == NULL) { return; }
     mech_mechanismID = (*env)->GetFieldID(env, tmpClass, "mechanism", "J");
@@ -127,6 +145,10 @@
     mech_pParameterID = (*env)->GetFieldID(env, tmpClass, "pParameter",
                                            "Ljava/lang/Object;");
     if (mech_pParameterID == NULL) { return; }
+    mech_pHandleID = (*env)->GetFieldID(env, tmpClass, "pHandle", "J");
+    if (mech_pHandleID == NULL) { return; }
+
+    /* java classes for primitive types - byte[], long */
     jByteArrayClass = fetchClass(env, "[B");
     if (jByteArrayClass == NULL) { return; }
     jLongClass = fetchClass(env, "java/lang/Long");
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_keymgmt.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_keymgmt.c	Wed Jun 12 10:02:49 2019 +0530
@@ -155,7 +155,7 @@
     jbyte* nativeKeyInfoArrayRawCkAttributes = NULL;
     jbyte* nativeKeyInfoArrayRawCkAttributesPtr = NULL;
     jbyte* nativeKeyInfoArrayRawDataPtr = NULL;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     char iv[16] = {0x0};
     CK_ULONG ckWrappedKeyLength = 0U;
     jbyte* wrappedKeySizeWrappedKeyArrayPtr = NULL;
@@ -310,8 +310,8 @@
         // Key is sensitive. Need to extract it wrapped.
         if (jWrappingKeyHandle != 0) {
 
-            jMechanismToCKMechanism(env, jWrappingMech, &ckMechanism);
-            rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism,
+            ckpMechanism = jMechanismToCKMechanismPtr(env, jWrappingMech);
+            rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism,
                     jLongToCKULong(jWrappingKeyHandle), ckObjectHandle,
                     NULL_PTR, &ckWrappedKeyLength);
             if (ckWrappedKeyLength != 0) {
@@ -339,7 +339,7 @@
                 wrappedKeyBufferPtr =
                         (CK_BYTE_PTR) (wrappedKeySizeWrappedKeyArrayPtr +
                         sizeof(unsigned long));
-                rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism,
+                rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism,
                         jLongToCKULong(jWrappingKeyHandle),ckObjectHandle,
                         wrappedKeyBufferPtr, &ckWrappedKeyLength);
                 if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
@@ -382,6 +382,7 @@
             && returnValue != nativeKeyInfoWrappedKeyArray) {
         (*env)->DeleteLocalRef(env, nativeKeyInfoWrappedKeyArray);
     }
+    freeCKMechanismPtr(ckpMechanism);
 
     return returnValue;
 }
@@ -417,7 +418,7 @@
     unsigned long totalDataSize = 0UL;
     jbyte* wrappedKeySizePtr = NULL;
     unsigned int i = 0U;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     char iv[16] = {0x0};
     CK_ULONG ckWrappedKeyLength = 0UL;
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -468,8 +469,8 @@
                 jLongToCKULong(nativeKeyInfoCkAttributesCount), &ckObjectHandle);
     } else {
         // Wrapped key
-        jMechanismToCKMechanism(env, jWrappingMech, &ckMechanism);
-        rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism,
+        ckpMechanism = jMechanismToCKMechanismPtr(env, jWrappingMech);
+        rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, ckpMechanism,
                 jLongToCKULong(jWrappingKeyHandle),
                 (CK_BYTE_PTR)(wrappedKeySizePtr + sizeof(unsigned long)),
                 ckWrappedKeyLength,
@@ -490,6 +491,7 @@
                 nativeKeyInfoArrayRaw, JNI_ABORT);
     }
 
+    freeCKMechanismPtr(ckpMechanism);
     return jObjectHandle;
 }
 #endif
@@ -510,9 +512,9 @@
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jobjectArray jTemplate)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
-    CK_ULONG ckAttributesLength;
+    CK_ULONG ckAttributesLength = 0;
     CK_OBJECT_HANDLE ckKeyHandle = 0;
     jlong jKeyHandle = 0L;
     CK_RV rv;
@@ -521,24 +523,21 @@
     if (ckpFunctions == NULL) { return 0L; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return 0L ; }
 
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        return 0L;
+        goto cleanup;
     }
 
-    rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, &ckMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
+    rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, ckpMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jKeyHandle = ckULongToJLong(ckKeyHandle);
 
         /* cheack, if we must give a initialization vector back to Java */
-        switch (ckMechanism.mechanism) {
+        switch (ckpMechanism->mechanism) {
         case CKM_PBE_MD2_DES_CBC:
         case CKM_PBE_MD5_DES_CBC:
         case CKM_PBE_MD5_CAST_CBC:
@@ -548,14 +547,12 @@
         case CKM_PBE_SHA1_CAST128_CBC:
         /* case CKM_PBE_SHA1_CAST5_CBC: the same as CKM_PBE_SHA1_CAST128_CBC */
             /* we must copy back the initialization vector to the jMechanism object */
-            copyBackPBEInitializationVector(env, &ckMechanism, jMechanism);
+            copyBackPBEInitializationVector(env, ckpMechanism, jMechanism);
             break;
         }
     }
-
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+cleanup:
+    freeCKMechanismPtr(ckpMechanism);
     freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     return jKeyHandle ;
@@ -582,14 +579,14 @@
      jobjectArray jPublicKeyTemplate, jobjectArray jPrivateKeyTemplate)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_ATTRIBUTE_PTR ckpPublicKeyAttributes = NULL_PTR;
     CK_ATTRIBUTE_PTR ckpPrivateKeyAttributes = NULL_PTR;
-    CK_ULONG ckPublicKeyAttributesLength;
-    CK_ULONG ckPrivateKeyAttributesLength;
+    CK_ULONG ckPublicKeyAttributesLength = 0;
+    CK_ULONG ckPrivateKeyAttributesLength = 0;
     CK_OBJECT_HANDLE_PTR ckpPublicKeyHandle;  /* pointer to Public Key */
     CK_OBJECT_HANDLE_PTR ckpPrivateKeyHandle; /* pointer to Private Key */
-    CK_OBJECT_HANDLE_PTR ckpKeyHandles;     /* pointer to array with Public and Private Key */
+    CK_OBJECT_HANDLE_PTR ckpKeyHandles = NULL; /* pointer to array with Public and Private Key */
     jlongArray jKeyHandles = NULL;
     CK_RV rv;
     int attempts;
@@ -599,37 +596,25 @@
     if (ckpFunctions == NULL) { return NULL; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     ckpKeyHandles = (CK_OBJECT_HANDLE_PTR) malloc(2 * sizeof(CK_OBJECT_HANDLE));
     if (ckpKeyHandles == NULL) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
         throwOutOfMemoryError(env, 0);
-        return NULL;
+        goto cleanup;
     }
     ckpPublicKeyHandle = ckpKeyHandles;   /* first element of array is Public Key */
     ckpPrivateKeyHandle = (ckpKeyHandles + 1);  /* second element of array is Private Key */
 
     jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        free(ckpKeyHandles);
-        return NULL;
+        goto cleanup;
     }
 
     jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        free(ckpKeyHandles);
-        freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
-        return NULL;
+        goto cleanup;
     }
 
     /*
@@ -650,7 +635,7 @@
      * Call C_GenerateKeyPair() several times if CKR_FUNCTION_FAILED occurs.
      */
     for (attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
-        rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, &ckMechanism,
+        rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, ckpMechanism,
                         ckpPublicKeyAttributes, ckPublicKeyAttributesLength,
                         ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength,
                         ckpPublicKeyHandle, ckpPrivateKeyHandle);
@@ -666,13 +651,11 @@
         jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
     }
 
-    if(ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+cleanup:
+    freeCKMechanismPtr(ckpMechanism);
     free(ckpKeyHandles);
     freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
     freeCKAttributeArray(ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength);
-
     return jKeyHandles ;
 }
 #endif
@@ -694,7 +677,7 @@
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jWrappingKeyHandle, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckWrappingKeyHandle;
     CK_OBJECT_HANDLE ckKeyHandle;
     jbyteArray jWrappedKey = NULL;
@@ -707,33 +690,30 @@
     if (ckpFunctions == NULL) { return NULL; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     ckWrappingKeyHandle = jLongToCKULong(jWrappingKeyHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
-    rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
+    rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     if (rv == CKR_BUFFER_TOO_SMALL) {
         ckpWrappedKey = (CK_BYTE_PTR) malloc(ckWrappedKeyLength);
         if (ckpWrappedKey == NULL) {
-            if (ckMechanism.pParameter != NULL_PTR) {
-                free(ckMechanism.pParameter);
-            }
             throwOutOfMemoryError(env, 0);
-            return NULL;
+            goto cleanup;
         }
 
-        rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
+        rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jWrappedKey = ckByteArrayToJByteArray(env, ckpWrappedKey, ckWrappedKeyLength);
     }
 
+cleanup:
     if (ckpWrappedKey != BUF) { free(ckpWrappedKey); }
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+    freeCKMechanismPtr(ckpMechanism);
+
     return jWrappedKey ;
 }
 #endif
@@ -758,12 +738,12 @@
      jbyteArray jWrappedKey, jobjectArray jTemplate)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckUnwrappingKeyHandle;
     CK_BYTE_PTR ckpWrappedKey = NULL_PTR;
     CK_ULONG ckWrappedKeyLength;
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
-    CK_ULONG ckAttributesLength;
+    CK_ULONG ckAttributesLength = 0;
     CK_OBJECT_HANDLE ckKeyHandle = 0;
     jlong jKeyHandle = 0L;
     CK_RV rv;
@@ -772,29 +752,22 @@
     if (ckpFunctions == NULL) { return 0L; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     ckUnwrappingKeyHandle = jLongToCKULong(jUnwrappingKeyHandle);
     jByteArrayToCKByteArray(env, jWrappedKey, &ckpWrappedKey, &ckWrappedKeyLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        return 0L;
+        goto cleanup;
     }
 
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        free(ckpWrappedKey);
-        return 0L;
+        goto cleanup;
     }
 
 
-    rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism, ckUnwrappingKeyHandle,
+    rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, ckpMechanism, ckUnwrappingKeyHandle,
                  ckpWrappedKey, ckWrappedKeyLength,
                  ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
@@ -803,16 +776,14 @@
 
 #if 0
         /* cheack, if we must give a initialization vector back to Java */
-        if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
+        if (ckpMechanism->mechanism == CKM_KEY_WRAP_SET_OAEP) {
             /* we must copy back the unwrapped key info to the jMechanism object */
-            copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
+            copyBackSetUnwrappedKey(env, ckpMechanism, jMechanism);
         }
 #endif
     }
-
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
+cleanup:
+    freeCKMechanismPtr(ckpMechanism);
     freeCKAttributeArray(ckpAttributes, ckAttributesLength);
     free(ckpWrappedKey);
 
@@ -834,26 +805,27 @@
     }
 }
 
-void ssl3FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckMechanism) {
-    CK_SSL3_MASTER_KEY_DERIVE_PARAMS *params = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) ckMechanism->pParameter;
+void ssl3FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckpMechanism) {
+    CK_SSL3_MASTER_KEY_DERIVE_PARAMS *params =
+            (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) ckpMechanism->pParameter;
     if (params == NULL) {
         return;
     }
     freeMasterKeyDeriveParams(&(params->RandomInfo), params->pVersion);
 }
 
-void tls12FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckMechanism) {
+void tls12FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckpMechanism) {
     CK_TLS12_MASTER_KEY_DERIVE_PARAMS *params =
-            (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
+            (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
     if (params == NULL) {
         return;
     }
     freeMasterKeyDeriveParams(&(params->RandomInfo), params->pVersion);
 }
 
-void freeEcdh1DeriveParams(CK_MECHANISM_PTR ckMechanism) {
+void freeEcdh1DeriveParams(CK_MECHANISM_PTR ckpMechanism) {
     CK_ECDH1_DERIVE_PARAMS *params =
-            (CK_ECDH1_DERIVE_PARAMS *)ckMechanism->pParameter;
+            (CK_ECDH1_DERIVE_PARAMS *)ckpMechanism->pParameter;
     if (params == NULL) {
         return;
     }
@@ -869,7 +841,7 @@
 /*
  * Copy back the PRF output to Java.
  */
-void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
+void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism, jobject jMechanism)
 {
     jclass jMechanismClass, jTLSPrfParamsClass;
     CK_TLS_PRF_PARAMS *ckTLSPrfParams;
@@ -890,13 +862,13 @@
     if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
-    if (ckMechanismType != ckMechanism->mechanism) {
+    if (ckMechanismType != ckpMechanism->mechanism) {
         /* we do not have maching types, this should not occur */
         return;
     }
 
     /* get the native CK_TLS_PRF_PARAMS */
-    ckTLSPrfParams = (CK_TLS_PRF_PARAMS *) ckMechanism->pParameter;
+    ckTLSPrfParams = (CK_TLS_PRF_PARAMS *) ckpMechanism->pParameter;
     if (ckTLSPrfParams != NULL_PTR) {
         /* get the Java CK_TLS_PRF_PARAMS object (pParameter) */
         fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
@@ -950,10 +922,10 @@
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jBaseKeyHandle, jobjectArray jTemplate)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckBaseKeyHandle;
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
-    CK_ULONG ckAttributesLength;
+    CK_ULONG ckAttributesLength = 0;
     CK_OBJECT_HANDLE ckKeyHandle = 0;
     jlong jKeyHandle = 0L;
     CK_RV rv;
@@ -963,19 +935,16 @@
     if (ckpFunctions == NULL) { return 0L; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     ckBaseKeyHandle = jLongToCKULong(jBaseKeyHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
     if ((*env)->ExceptionCheck(env)) {
-        if (ckMechanism.pParameter != NULL_PTR) {
-            free(ckMechanism.pParameter);
-        }
-        return 0L;
+        goto cleanup;
     }
 
-    switch (ckMechanism.mechanism) {
+    switch (ckpMechanism->mechanism) {
     case CKM_SSL3_KEY_AND_MAC_DERIVE:
     case CKM_TLS_KEY_AND_MAC_DERIVE:
     case CKM_TLS12_KEY_AND_MAC_DERIVE:
@@ -989,60 +958,60 @@
         break;
     }
 
-    rv = (*ckpFunctions->C_DeriveKey)(ckSessionHandle, &ckMechanism, ckBaseKeyHandle,
+    rv = (*ckpFunctions->C_DeriveKey)(ckSessionHandle, ckpMechanism, ckBaseKeyHandle,
                  ckpAttributes, ckAttributesLength, phKey);
 
     jKeyHandle = ckLongToJLong(ckKeyHandle);
 
-    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
-
-    switch (ckMechanism.mechanism) {
+    switch (ckpMechanism->mechanism) {
     case CKM_SSL3_MASTER_KEY_DERIVE:
     case CKM_TLS_MASTER_KEY_DERIVE:
         /* we must copy back the client version */
-        ssl3CopyBackClientVersion(env, &ckMechanism, jMechanism);
-        ssl3FreeMasterKeyDeriveParams(&ckMechanism);
+        ssl3CopyBackClientVersion(env, ckpMechanism, jMechanism);
+        ssl3FreeMasterKeyDeriveParams(ckpMechanism);
         break;
     case CKM_TLS12_MASTER_KEY_DERIVE:
-        tls12CopyBackClientVersion(env, &ckMechanism, jMechanism);
-        tls12FreeMasterKeyDeriveParams(&ckMechanism);
+        tls12CopyBackClientVersion(env, ckpMechanism, jMechanism);
+        tls12FreeMasterKeyDeriveParams(ckpMechanism);
         break;
     case CKM_SSL3_MASTER_KEY_DERIVE_DH:
     case CKM_TLS_MASTER_KEY_DERIVE_DH:
-        ssl3FreeMasterKeyDeriveParams(&ckMechanism);
+        ssl3FreeMasterKeyDeriveParams(ckpMechanism);
         break;
     case CKM_TLS12_MASTER_KEY_DERIVE_DH:
-        tls12FreeMasterKeyDeriveParams(&ckMechanism);
+        tls12FreeMasterKeyDeriveParams(ckpMechanism);
         break;
     case CKM_SSL3_KEY_AND_MAC_DERIVE:
     case CKM_TLS_KEY_AND_MAC_DERIVE:
         /* we must copy back the unwrapped key info to the jMechanism object */
-        ssl3CopyBackKeyMatParams(env, &ckMechanism, jMechanism);
+        ssl3CopyBackKeyMatParams(env, ckpMechanism, jMechanism);
         break;
     case CKM_TLS12_KEY_AND_MAC_DERIVE:
         /* we must copy back the unwrapped key info to the jMechanism object */
-        tls12CopyBackKeyMatParams(env, &ckMechanism, jMechanism);
+        tls12CopyBackKeyMatParams(env, ckpMechanism, jMechanism);
         break;
     case CKM_TLS_PRF:
-        copyBackTLSPrfParams(env, &ckMechanism, jMechanism);
+        copyBackTLSPrfParams(env, ckpMechanism, jMechanism);
         break;
     case CKM_ECDH1_DERIVE:
-        freeEcdh1DeriveParams(&ckMechanism);
+        freeEcdh1DeriveParams(ckpMechanism);
         break;
     default:
         // empty
         break;
     }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        jKeyHandle =0L;
+    }
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
-    }
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+cleanup:
+    freeCKMechanismPtr(ckpMechanism);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     return jKeyHandle ;
 }
 
-static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism,
+static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism, jobject jMechanism,
         CK_VERSION *ckVersion, const char *class_master_key_derive_params)
 {
     jclass jMasterKeyDeriveParamsClass, jMechanismClass, jVersionClass;
@@ -1059,7 +1028,7 @@
     if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
-    if (ckMechanismType != ckMechanism->mechanism) {
+    if (ckMechanismType != ckpMechanism->mechanism) {
         /* we do not have maching types, this should not occur */
         return;
     }
@@ -1102,14 +1071,14 @@
  * mechanisms when used for deriving a key.
  *
  */
-void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism,
+void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
         jobject jMechanism)
 {
     CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ckSSL3MasterKeyDeriveParams;
     ckSSL3MasterKeyDeriveParams =
-            (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
+            (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
     if (ckSSL3MasterKeyDeriveParams != NULL_PTR) {
-        copyBackClientVersion(env, ckMechanism, jMechanism,
+        copyBackClientVersion(env, ckpMechanism, jMechanism,
                 ckSSL3MasterKeyDeriveParams->pVersion,
                 CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
     }
@@ -1121,20 +1090,20 @@
  * CKM_TLS12_MASTER_KEY_DERIVE mechanism when used for deriving a key.
  *
  */
-void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism,
+void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
         jobject jMechanism)
 {
     CK_TLS12_MASTER_KEY_DERIVE_PARAMS *ckTLS12MasterKeyDeriveParams;
     ckTLS12MasterKeyDeriveParams =
-            (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
+            (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
     if (ckTLS12MasterKeyDeriveParams != NULL_PTR) {
-        copyBackClientVersion(env, ckMechanism, jMechanism,
+        copyBackClientVersion(env, ckpMechanism, jMechanism,
                 ckTLS12MasterKeyDeriveParams->pVersion,
                 CLASS_TLS12_MASTER_KEY_DERIVE_PARAMS);
     }
 }
 
-static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
+static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
         jobject jMechanism, CK_SSL3_RANDOM_DATA *RandomInfo,
         CK_SSL3_KEY_MAT_OUT_PTR ckSSL3KeyMatOut, const char *class_key_mat_params)
 {
@@ -1157,7 +1126,7 @@
     if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
-    if (ckMechanismType != ckMechanism->mechanism) {
+    if (ckMechanismType != ckpMechanism->mechanism) {
         /* we do not have maching types, this should not occur */
         return;
     }
@@ -1264,13 +1233,13 @@
  * when used for deriving a key.
  *
  */
-void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
+void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
         jobject jMechanism)
 {
     CK_SSL3_KEY_MAT_PARAMS *ckSSL3KeyMatParam;
-    ckSSL3KeyMatParam = (CK_SSL3_KEY_MAT_PARAMS *)ckMechanism->pParameter;
+    ckSSL3KeyMatParam = (CK_SSL3_KEY_MAT_PARAMS *)ckpMechanism->pParameter;
     if (ckSSL3KeyMatParam != NULL_PTR) {
-        copyBackKeyMatParams(env, ckMechanism, jMechanism,
+        copyBackKeyMatParams(env, ckpMechanism, jMechanism,
                 &(ckSSL3KeyMatParam->RandomInfo),
                 ckSSL3KeyMatParam->pReturnedKeyMaterial,
                 CLASS_SSL3_KEY_MAT_PARAMS);
@@ -1283,13 +1252,13 @@
  * CKM_TLS12_KEY_AND_MAC_DERIVE mechanism when used for deriving a key.
  *
  */
-void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
+void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
         jobject jMechanism)
 {
     CK_TLS12_KEY_MAT_PARAMS *ckTLS12KeyMatParam;
-    ckTLS12KeyMatParam = (CK_TLS12_KEY_MAT_PARAMS *) ckMechanism->pParameter;
+    ckTLS12KeyMatParam = (CK_TLS12_KEY_MAT_PARAMS *)ckpMechanism->pParameter;
     if (ckTLS12KeyMatParam != NULL_PTR) {
-        copyBackKeyMatParams(env, ckMechanism, jMechanism,
+        copyBackKeyMatParams(env, ckpMechanism, jMechanism,
                 &(ckTLS12KeyMatParam->RandomInfo),
                 ckTLS12KeyMatParam->pReturnedKeyMaterial,
                 CLASS_TLS12_KEY_MAT_PARAMS);
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_mutex.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_mutex.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -181,7 +181,7 @@
     jReserved = (*env)->GetObjectField(env, jInitArgs, fieldID);
 
     /* we try to convert the reserved parameter also */
-    jObjectToPrimitiveCKObjectPtrPtr(env, jReserved, &(ckpInitArgs->pReserved), &ckReservedLength);
+    ckpInitArgs->pReserved = jObjectToPrimitiveCKObjectPtr(env, jReserved, &ckReservedLength);
 
     return ckpInitArgs ;
 }
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_sign.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_sign.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -63,31 +63,38 @@
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
  * @param   jobject jMechanism          CK_MECHANISM_PTR pMechanism
- * @return  jlong jKeyHandle            CK_OBJECT_HANDLE hKey
+ * @param   jlong jKeyHandle            CK_OBJECT_HANDLE hKey
  */
 JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignInit
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
+    TRACE0("DEBUG: C_SignInit\n");
+
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
-    rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
+    rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
+            (ckpMechanism->pParameter == NULL)) {
+        freeCKMechanismPtr(ckpMechanism);
+    } else {
+        (*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
+        TRACE1("DEBUG C_SignInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
     }
-
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    TRACE0("FINISHED\n");
 }
 #endif
 
@@ -95,7 +102,7 @@
 /*
  * Class:     sun_security_pkcs11_wrapper_PKCS11
  * Method:    C_Sign
- * Signature: (J[B)[B
+ * Signature: (J[BI)[B
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
  * @param   jbyteArray jData            CK_BYTE_PTR pData
@@ -108,69 +115,45 @@
 {
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpData = NULL_PTR;
-    CK_BYTE_PTR ckpSignature;
     CK_ULONG ckDataLength;
-    CK_ULONG ckSignatureLength = 0;
+    CK_BYTE_PTR bufP;
+    CK_ULONG ckSignatureLength;
+    CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
     jbyteArray jSignature = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return NULL; }
 
+    TRACE0("DEBUG: C_Sign\n");
+
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
-    if ((*env)->ExceptionCheck(env)) { return NULL; }
-
-    /* START standard code */
-
-    /* first determine the length of the signature */
-    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, NULL_PTR, &ckSignatureLength);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-        free(ckpData);
-        return NULL;
-    }
-
-    ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
-    if (ckpSignature == NULL) {
-        free(ckpData);
-        throwOutOfMemoryError(env, 0);
+    if ((*env)->ExceptionCheck(env)) {
         return NULL;
     }
 
-    /* now get the signature */
-    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
- /* END standard code */
-
+    TRACE1("DEBUG C_Sign: data length = %lu\n", ckDataLength);
 
-    /* START workaround code for operation abort bug in pkcs#11 of Datakey and iButton */
-/*
-    ckpSignature = (CK_BYTE_PTR) malloc(256 * sizeof(CK_BYTE));
-    if (ckpSignature == NULL) {
-        free(ckpData);
-        throwOutOfMemoryError(env, 0);
-        return NULL;
-    }
-    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
+    // unknown signature length
+    bufP = BUF;
+    ckSignatureLength = MAX_STACK_BUFFER_LEN;
+
+    rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength,
+        bufP, &ckSignatureLength);
+
+    TRACE1("DEBUG C_Sign: ret rv=0x%lX\n", rv);
 
-    if (rv == CKR_BUFFER_TOO_SMALL) {
-        free(ckpSignature);
-        ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
-        if (ckpSignature == NULL) {
-            free(ckpData);
-            throwOutOfMemoryError(env, 0);
-            return NULL;
-        }
-        rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSignature = ckByteArrayToJByteArray(env, bufP, ckSignatureLength);
+        TRACE1("DEBUG C_Sign: signature length = %lu\n", ckSignatureLength);
     }
- */
-    /* END workaround code */
-    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
-        jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
-    }
+
     free(ckpData);
-    free(ckpSignature);
+    if (bufP != BUF) { free(bufP); }
 
-    return jSignature ;
+    TRACE0("FINISHED\n");
+    return jSignature;
 }
 #endif
 
@@ -220,21 +203,20 @@
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
         if ((*env)->ExceptionCheck(env)) {
-            if (bufP != BUF) { free(bufP); }
-            return;
+            goto cleanup;
         }
         rv = (*ckpFunctions->C_SignUpdate)(ckSessionHandle, bufP, chunkLen);
         if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) {
-                free(bufP);
-            }
-            return;
+            goto cleanup;
         }
         jInOfs += chunkLen;
         jInLen -= chunkLen;
     }
 
+cleanup:
     if (bufP != BUF) { free(bufP); }
+
+    return;
 }
 #endif
 
@@ -294,32 +276,37 @@
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
  * @param   jobject jMechanism          CK_MECHANISM_PTR pMechanism
- * @return  jlong jKeyHandle            CK_OBJECT_HANDLE hKey
+ * @param   jlong jKeyHandle            CK_OBJECT_HANDLE hKey
  */
 JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignRecoverInit
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
+    TRACE0("DEBUG: C_SignRecoverInit\n");
+
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
 
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
-    rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
+    rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
+            (ckpMechanism->pParameter == NULL)) {
+        freeCKMechanismPtr(ckpMechanism);
+    } else {
+        (*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
+        TRACE1("DEBUG C_SignRecoverInit, stored pMech = 0x%lX\n", (jlong)ckpMechanism);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    TRACE0("FINISHED\n");
 }
 #endif
 
@@ -344,7 +331,7 @@
     CK_BYTE OUTBUF[MAX_STACK_BUFFER_LEN];
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP = OUTBUF;
-    CK_ULONG ckSignatureLength = MAX_STACK_BUFFER_LEN;
+    CK_ULONG ckSignatureLength = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
@@ -353,36 +340,35 @@
 
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
+        ckSignatureLength = MAX_STACK_BUFFER_LEN;
     } else {
         inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
         if (inBufP == NULL) {
             throwOutOfMemoryError(env, 0);
             return 0;
         }
+        ckSignatureLength = jInLen;
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
     if ((*env)->ExceptionCheck(env)) {
-        if (inBufP != INBUF) { free(inBufP); }
-        return 0;
+        goto cleanup;
     }
+
     rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     /* re-alloc larger buffer if it fits into our Java buffer */
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckSignatureLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
         if (outBufP == NULL) {
-            if (inBufP != INBUF) {
-                free(inBufP);
-            }
             throwOutOfMemoryError(env, 0);
-            return 0;
+            goto cleanup;
         }
         rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckSignatureLength, (jbyte *)outBufP);
     }
-
+cleanup:
     if (inBufP != INBUF) { free(inBufP); }
     if (outBufP != OUTBUF) { free(outBufP); }
 
@@ -398,32 +384,39 @@
  * Parametermapping:                    *PKCS11*
  * @param   jlong jSessionHandle        CK_SESSION_HANDLE hSession
  * @param   jobject jMechanism          CK_MECHANISM_PTR pMechanism
- * @return  jlong jKeyHandle            CK_OBJECT_HANDLE hKey
+ * @param   jlong jKeyHandle            CK_OBJECT_HANDLE hKey
  */
 JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyInit
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
+    TRACE0("DEBUG: C_VerifyInit\n");
+
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
-    if ((*env)->ExceptionCheck(env)) { return; }
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
+    if ((*env)->ExceptionCheck(env)) {
+        return;
+    }
 
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
-    rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
+    rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
+            (ckpMechanism->pParameter == NULL)) {
+        freeCKMechanismPtr(ckpMechanism);
+    } else {
+        (*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
+        TRACE1("DEBUG C_VerifyInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
     }
-
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    TRACE0("FINISHED\n");
 }
 #endif
 
@@ -447,28 +440,31 @@
     CK_BYTE_PTR ckpSignature = NULL_PTR;
     CK_ULONG ckDataLength;
     CK_ULONG ckSignatureLength;
-    CK_RV rv;
+    CK_RV rv = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
+
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
-    if ((*env)->ExceptionCheck(env)) { return; }
+    if ((*env)->ExceptionCheck(env)) {
+        return;
+    }
 
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
     if ((*env)->ExceptionCheck(env)) {
-        free(ckpData);
-        return;
+        goto cleanup;
     }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_Verify)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, ckSignatureLength);
 
+cleanup:
     free(ckpData);
     free(ckpSignature);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    ckAssertReturnValueOK(env, rv);
 }
 #endif
 
@@ -510,7 +506,7 @@
         bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
         if (bufP == NULL) {
             throwOutOfMemoryError(env, 0);
-            return;
+            goto cleanup;
         }
     }
 
@@ -518,19 +514,18 @@
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
         if ((*env)->ExceptionCheck(env)) {
-            if (bufP != BUF) { free(bufP); }
-            return;
+            goto cleanup;
         }
 
         rv = (*ckpFunctions->C_VerifyUpdate)(ckSessionHandle, bufP, chunkLen);
         if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) { free(bufP); }
-            return;
+            goto cleanup;
         }
         jInOfs += chunkLen;
         jInLen -= chunkLen;
     }
 
+cleanup:
     if (bufP != BUF) { free(bufP); }
 }
 #endif
@@ -558,14 +553,16 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
-    if ((*env)->ExceptionCheck(env)) { return; }
+    if ((*env)->ExceptionCheck(env)) {
+        return;
+    }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_VerifyFinal)(ckSessionHandle, ckpSignature, ckSignatureLength);
 
     free(ckpSignature);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    ckAssertReturnValueOK(env, rv);
 }
 #endif
 
@@ -583,26 +580,31 @@
     (JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
 {
     CK_SESSION_HANDLE ckSessionHandle;
-    CK_MECHANISM ckMechanism;
+    CK_MECHANISM_PTR ckpMechanism = NULL;
     CK_OBJECT_HANDLE ckKeyHandle;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return; }
 
+    TRACE0("DEBUG: C_VerifyRecoverInit\n");
+
     ckSessionHandle = jLongToCKULong(jSessionHandle);
-    jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
     if ((*env)->ExceptionCheck(env)) { return; }
 
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
-    rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
+    rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
 
-    if (ckMechanism.pParameter != NULL_PTR) {
-        free(ckMechanism.pParameter);
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
+            (ckpMechanism->pParameter == NULL)) {
+        freeCKMechanismPtr(ckpMechanism);
+    } else {
+        (*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
+        TRACE1("DEBUG C_VerifyRecoverInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
     }
-
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    TRACE0("FINISHED\n");
 }
 #endif
 
@@ -627,7 +629,7 @@
     CK_BYTE OUTBUF[MAX_STACK_BUFFER_LEN];
     CK_BYTE_PTR inBufP;
     CK_BYTE_PTR outBufP = OUTBUF;
-    CK_ULONG ckDataLength = MAX_STACK_BUFFER_LEN;
+    CK_ULONG ckDataLength = 0;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
     if (ckpFunctions == NULL) { return 0; }
@@ -636,18 +638,19 @@
 
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
+        ckDataLength = MAX_STACK_BUFFER_LEN;
     } else {
         inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
         if (inBufP == NULL) {
             throwOutOfMemoryError(env, 0);
             return 0;
         }
+        ckDataLength = jInLen;
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
     if ((*env)->ExceptionCheck(env)) {
-        if (inBufP != INBUF) { free(inBufP); }
-        return 0;
+        goto cleanup;
     }
 
     rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
@@ -656,9 +659,8 @@
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckDataLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckDataLength);
         if (outBufP == NULL) {
-            if (inBufP != INBUF) { free(inBufP); }
             throwOutOfMemoryError(env, 0);
-            return 0;
+            goto cleanup;
         }
         rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
     }
@@ -666,6 +668,7 @@
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckDataLength, (jbyte *)outBufP);
     }
 
+cleanup:
     if (inBufP != INBUF) { free(inBufP); }
     if (outBufP != OUTBUF) { free(outBufP); }
 
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_util.c	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/p11_util.c	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -277,16 +277,32 @@
  * @param attrPtr pointer to the to-be-freed CK_ATTRIBUTE array.
  * @param len the length of the array
  */
-void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len)
-{
-    int i;
+void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len) {
+    if (attrPtr != NULL) {
+        int i;
+        for (i=0; i<len; i++) {
+            if (attrPtr[i].pValue != NULL_PTR) {
+                free(attrPtr[i].pValue);
+            }
+        }
+        free(attrPtr);
+    }
+}
 
-    for (i=0; i<len; i++) {
-        if (attrPtr[i].pValue != NULL_PTR) {
-            free(attrPtr[i].pValue);
-        }
-    }
-    free(attrPtr);
+/* This function frees the specified CK_MECHANISM_PTR pointer and its
+ * pParameter. NOTE: mechanism-specific memory allocations have to be
+ * freed before this call as this method only frees the generic
+ * memory associated with CK_MECHANISM structure.
+ *
+ * @param mechPtr pointer to the to-be-freed CK_MECHANISM structure.
+ */
+
+void freeCKMechanismPtr(CK_MECHANISM_PTR mechPtr) {
+     if (mechPtr != NULL) {
+         TRACE1("DEBUG: free CK_MECHANISM %x", mechPtr);
+         free(mechPtr->pParameter);
+         free(mechPtr);
+     }
 }
 
 /*
@@ -964,165 +980,164 @@
 
 /*
  * converts a Java object into a pointer to CK-type or a CK-structure with the length in Bytes.
- * The memory of *ckpObjectPtr to be freed after use! This function is only used by
- * jAttributeToCKAttribute by now.
+ * The memory of the returned pointer MUST BE FREED BY CALLER!
  *
  * @param env - used to call JNI funktions to get the Java classes and objects
  * @param jObject - the Java object to convert
- * @param ckpObjectPtr - the reference of the new pointer to the new CK-value or CK-structure
- * @param ckpLength - the reference of the length in bytes of the new CK-value or CK-structure
+ * @param ckpLength - pointer to the length (bytes) of the newly-allocated CK-value or CK-structure
+ * @return ckpObject - pointer to the newly-allocated CK-value or CK-structure
  */
-void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *ckpLength)
+CK_VOID_PTR jObjectToPrimitiveCKObjectPtr(JNIEnv *env, jobject jObject, CK_ULONG *ckpLength)
 {
     jclass jLongClass, jBooleanClass, jByteArrayClass, jCharArrayClass;
     jclass jByteClass, jDateClass, jCharacterClass, jIntegerClass;
     jclass jBooleanArrayClass, jIntArrayClass, jLongArrayClass;
     jclass jStringClass;
     jclass jObjectClass, jClassClass;
-    CK_VOID_PTR ckpVoid = *ckpObjectPtr;
+    CK_VOID_PTR ckpObject;
     jmethodID jMethod;
     jobject jClassObject;
     jstring jClassNameString;
     char *classNameString, *exceptionMsgPrefix, *exceptionMsg;
 
-    TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtrPtr");
+    TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtr");
     if (jObject == NULL) {
-        *ckpObjectPtr = NULL;
         *ckpLength = 0;
-        return;
+        return NULL;
     }
 
     jLongClass = (*env)->FindClass(env, "java/lang/Long");
-    if (jLongClass == NULL) { return; }
+    if (jLongClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
-        *ckpObjectPtr = jLongObjectToCKULongPtr(env, jObject);
+        ckpObject = jLongObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
-        TRACE1("<converted long value %X>", *((CK_ULONG *) *ckpObjectPtr));
-        return;
+        TRACE1("<converted long value %X>", *((CK_ULONG *) ckpObject));
+        return ckpObject;
     }
 
     jBooleanClass = (*env)->FindClass(env, "java/lang/Boolean");
-    if (jBooleanClass == NULL) { return; }
+    if (jBooleanClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
-        *ckpObjectPtr = jBooleanObjectToCKBBoolPtr(env, jObject);
+        ckpObject = jBooleanObjectToCKBBoolPtr(env, jObject);
         *ckpLength = sizeof(CK_BBOOL);
         TRACE0(" <converted boolean value ");
-        TRACE0((*((CK_BBOOL *) *ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
-        return;
+        TRACE0((*((CK_BBOOL *) ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
+        return ckpObject;
     }
 
     jByteArrayClass = (*env)->FindClass(env, "[B");
-    if (jByteArrayClass == NULL) { return; }
+    if (jByteArrayClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
-        jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*)ckpObjectPtr, ckpLength);
-        return;
+        jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     jCharArrayClass = (*env)->FindClass(env, "[C");
-    if (jCharArrayClass == NULL) { return; }
+    if (jCharArrayClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
-        jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
-        return;
+        jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     jByteClass = (*env)->FindClass(env, "java/lang/Byte");
-    if (jByteClass == NULL) { return; }
+    if (jByteClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
-        *ckpObjectPtr = jByteObjectToCKBytePtr(env, jObject);
+        ckpObject = jByteObjectToCKBytePtr(env, jObject);
         *ckpLength = sizeof(CK_BYTE);
-        TRACE1("<converted byte value %X>", *((CK_BYTE *) *ckpObjectPtr));
-        return;
+        TRACE1("<converted byte value %X>", *((CK_BYTE *) ckpObject));
+        return ckpObject;
     }
 
     jDateClass = (*env)->FindClass(env, CLASS_DATE);
-    if (jDateClass == NULL) { return; }
+    if (jDateClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
-        *ckpObjectPtr = jDateObjectPtrToCKDatePtr(env, jObject);
+        ckpObject = jDateObjectPtrToCKDatePtr(env, jObject);
         *ckpLength = sizeof(CK_DATE);
-        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year, (*((CK_DATE *) *ckpObjectPtr)).month, (*((CK_DATE *) *ckpObjectPtr)).day);
-        return;
+        TRACE3("<converted date value %.4s-%.2s-%.2s>", ((CK_DATE *) ckpObject)->year,
+                ((CK_DATE *) ckpObject)->month, ((CK_DATE *) ckpObject)->day);
+        return ckpObject;
     }
 
     jCharacterClass = (*env)->FindClass(env, "java/lang/Character");
-    if (jCharacterClass == NULL) { return; }
+    if (jCharacterClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
-        *ckpObjectPtr = jCharObjectToCKCharPtr(env, jObject);
+        ckpObject = jCharObjectToCKCharPtr(env, jObject);
         *ckpLength = sizeof(CK_UTF8CHAR);
-        TRACE1("<converted char value %c>", *((CK_CHAR *) *ckpObjectPtr));
-        return;
+        TRACE1("<converted char value %c>", *((CK_CHAR *) ckpObject));
+        return ckpObject;
     }
 
     jIntegerClass = (*env)->FindClass(env, "java/lang/Integer");
-    if (jIntegerClass == NULL) { return; }
+    if (jIntegerClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
-        *ckpObjectPtr = jIntegerObjectToCKULongPtr(env, jObject);
+        ckpObject = jIntegerObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
-        TRACE1("<converted integer value %X>", *((CK_ULONG *) *ckpObjectPtr));
-        return;
+        TRACE1("<converted integer value %X>", *((CK_ULONG *) ckpObject));
+        return ckpObject;
     }
 
     jBooleanArrayClass = (*env)->FindClass(env, "[Z");
-    if (jBooleanArrayClass == NULL) { return; }
+    if (jBooleanArrayClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
-        jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**)ckpObjectPtr, ckpLength);
-        return;
+        jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     jIntArrayClass = (*env)->FindClass(env, "[I");
-    if (jIntArrayClass == NULL) { return; }
+    if (jIntArrayClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
-        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-        return;
+        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     jLongArrayClass = (*env)->FindClass(env, "[J");
-    if (jLongArrayClass == NULL) { return; }
+    if (jLongArrayClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
-        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-        return;
+        jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     jStringClass = (*env)->FindClass(env, "java/lang/String");
-    if (jStringClass == NULL) { return; }
+    if (jStringClass == NULL) { return NULL; }
     if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
-        jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
-        return;
+        jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*) &ckpObject, ckpLength);
+        return ckpObject;
     }
 
     /* type of jObject unknown, throw PKCS11RuntimeException */
     jObjectClass = (*env)->FindClass(env, "java/lang/Object");
-    if (jObjectClass == NULL) { return; }
+    if (jObjectClass == NULL) { return NULL; }
     jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
-    if (jMethod == NULL) { return; }
+    if (jMethod == NULL) { return NULL; }
     jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
     assert(jClassObject != 0);
     jClassClass = (*env)->FindClass(env, "java/lang/Class");
-    if (jClassClass == NULL) { return; }
+    if (jClassClass == NULL) { return NULL; }
     jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
-    if (jMethod == NULL) { return; }
+    if (jMethod == NULL) { return NULL; }
     jClassNameString = (jstring)
         (*env)->CallObjectMethod(env, jClassObject, jMethod);
     assert(jClassNameString != 0);
     classNameString = (char*)
         (*env)->GetStringUTFChars(env, jClassNameString, NULL);
-    if (classNameString == NULL) { return; }
+    if (classNameString == NULL) { return NULL; }
     exceptionMsgPrefix = "Java object of this class cannot be converted to native PKCS#11 type: ";
     exceptionMsg = (char *)
         malloc((strlen(exceptionMsgPrefix) + strlen(classNameString) + 1));
     if (exceptionMsg == NULL) {
         (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
         throwOutOfMemoryError(env, 0);
-        return;
+        return NULL;
     }
     strcpy(exceptionMsg, exceptionMsgPrefix);
     strcat(exceptionMsg, classNameString);
     (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
     throwPKCS11RuntimeException(env, exceptionMsg);
     free(exceptionMsg);
-    *ckpObjectPtr = NULL;
     *ckpLength = 0;
 
     TRACE0("FINISHED\n");
+    return NULL;
 }
 
 #ifdef P11_MEMORYDEBUG
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs-11v2-20a3.h	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,124 +0,0 @@
-/* pkcs-11v2-20a3.h include file for the PKCS #11 Version 2.20 Amendment 3
-   document. */
-
-/* $Revision: 1.4 $ */
-
-/* License to copy and use this software is granted provided that it is
- * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
- * (Cryptoki) Version 2.20 Amendment 3" in all material mentioning or
- * referencing this software.
-
- * RSA Security Inc. makes no representations concerning either the
- * merchantability of this software or the suitability of this software for
- * any particular purpose. It is provided "as is" without express or implied
- * warranty of any kind.
- */
-
-/* This file is preferably included after inclusion of pkcs11.h */
-
-#ifndef _PKCS_11V2_20A3_H_
-#define _PKCS_11V2_20A3_H_ 1
-
-/* Are the definitions of this file already included in pkcs11t.h ? */
-#ifndef CKK_CAMELLIA
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Key types */
-
-/* Camellia is new for PKCS #11 v2.20 amendment 3 */
-#define CKK_CAMELLIA                   0x00000025
-/* ARIA is new for PKCS #11 v2.20 amendment 3 */
-#define CKK_ARIA                       0x00000026
-
-
-/* Mask-generating functions */
-
-/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
-#define CKG_MGF1_SHA224                0x00000005
-
-
-/* Mechanism Identifiers */
-
-/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
-#define CKM_SHA224                     0x00000255
-#define CKM_SHA224_HMAC                0x00000256
-#define CKM_SHA224_HMAC_GENERAL        0x00000257
-
-/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */
-#define CKM_SHA224_KEY_DERIVATION      0x00000396
-
-/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */
-#define CKM_SHA224_RSA_PKCS            0x00000046
-#define CKM_SHA224_RSA_PKCS_PSS        0x00000047
-
-/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */
-#define CKM_AES_CTR                    0x00001086
-
-/* Camellia is new for PKCS #11 v2.20 amendment 3 */
-#define CKM_CAMELLIA_KEY_GEN           0x00000550
-#define CKM_CAMELLIA_ECB               0x00000551
-#define CKM_CAMELLIA_CBC               0x00000552
-#define CKM_CAMELLIA_MAC               0x00000553
-#define CKM_CAMELLIA_MAC_GENERAL       0x00000554
-#define CKM_CAMELLIA_CBC_PAD           0x00000555
-#define CKM_CAMELLIA_ECB_ENCRYPT_DATA  0x00000556
-#define CKM_CAMELLIA_CBC_ENCRYPT_DATA  0x00000557
-#define CKM_CAMELLIA_CTR               0x00000558
-
-/* ARIA is new for PKCS #11 v2.20 amendment 3 */
-#define CKM_ARIA_KEY_GEN               0x00000560
-#define CKM_ARIA_ECB                   0x00000561
-#define CKM_ARIA_CBC                   0x00000562
-#define CKM_ARIA_MAC                   0x00000563
-#define CKM_ARIA_MAC_GENERAL           0x00000564
-#define CKM_ARIA_CBC_PAD               0x00000565
-#define CKM_ARIA_ECB_ENCRYPT_DATA      0x00000566
-#define CKM_ARIA_CBC_ENCRYPT_DATA      0x00000567
-
-
-/* Mechanism parameters */
-
-/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
-typedef struct CK_AES_CTR_PARAMS {
-    CK_ULONG ulCounterBits;
-    CK_BYTE cb[16];
-} CK_AES_CTR_PARAMS;
-
-typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;
-
-/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
-typedef struct CK_CAMELLIA_CTR_PARAMS {
-    CK_ULONG ulCounterBits;
-    CK_BYTE cb[16];
-} CK_CAMELLIA_CTR_PARAMS;
-
-typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR;
-
-/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
-typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS {
-    CK_BYTE      iv[16];
-    CK_BYTE_PTR  pData;
-    CK_ULONG     length;
-} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS;
-
-typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
-
-/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
-typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS {
-    CK_BYTE      iv[16];
-    CK_BYTE_PTR  pData;
-    CK_ULONG     length;
-} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS;
-
-typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-#endif
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h	Wed Jun 12 10:02:49 2019 +0530
@@ -1,19 +1,12 @@
-/* pkcs11.h include file for PKCS #11. */
-/* $Revision: 1.4 $ */
-
-/* License to copy and use this software is granted provided that it is
- * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
- * (Cryptoki)" in all material mentioning or referencing this software.
+/* Copyright (c) OASIS Open 2016. All Rights Reserved./
+ * /Distributed under the terms of the OASIS IPR Policy,
+ * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
+ * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
+ */
 
- * License is also granted to make and use derivative works provided that
- * such works are identified as "derived from the RSA Security Inc. PKCS #11
- * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
- * referencing the derived work.
-
- * RSA Security Inc. makes no representations concerning either the
- * merchantability of this software or the suitability of this software for
- * any particular purpose. It is provided "as is" without express or implied
- * warranty of any kind.
+/* Latest version of the specification:
+ * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
  */
 
 #ifndef _PKCS11_H_
@@ -24,14 +17,14 @@
 #endif
 
 /* Before including this file (pkcs11.h) (or pkcs11t.h by
- * itself), 6 platform-specific macros must be defined.  These
+ * itself), 5 platform-specific macros must be defined.  These
  * macros are described below, and typical definitions for them
  * are also given.  Be advised that these definitions can depend
  * on both the platform and the compiler used (and possibly also
  * on whether a Cryptoki library is linked statically or
  * dynamically).
  *
- * In addition to defining these 6 macros, the packing convention
+ * In addition to defining these 5 macros, the packing convention
  * for Cryptoki structures should be set.  The Cryptoki
  * convention on packing is that structures should be 1-byte
  * aligned.
@@ -81,39 +74,7 @@
  * #define CK_PTR *
  *
  *
- * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes
- * an exportable Cryptoki library function definition out of a
- * return type and a function name.  It should be used in the
- * following fashion to define the exposed Cryptoki functions in
- * a Cryptoki library:
- *
- * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)(
- *   CK_VOID_PTR pReserved
- * )
- * {
- *   ...
- * }
- *
- * If you're using Microsoft Developer Studio 5.0 to define a
- * function in a Win32 Cryptoki .dll, it might be defined by:
- *
- * #define CK_DEFINE_FUNCTION(returnType, name) \
- *   returnType __declspec(dllexport) name
- *
- * If you're using an earlier version of Microsoft Developer
- * Studio to define a function in a Win16 Cryptoki .dll, it
- * might be defined by:
- *
- * #define CK_DEFINE_FUNCTION(returnType, name) \
- *   returnType __export _far _pascal name
- *
- * In a UNIX environment, it might be defined by:
- *
- * #define CK_DEFINE_FUNCTION(returnType, name) \
- *   returnType name
- *
- *
- * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
+ * 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
  * an importable Cryptoki library function declaration out of a
  * return type and a function name.  It should be used in the
  * following fashion:
@@ -141,7 +102,7 @@
  *   returnType name
  *
  *
- * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
+ * 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
  * which makes a Cryptoki API function pointer declaration or
  * function pointer type declaration out of a return type and a
  * function name.  It should be used in the following fashion:
@@ -178,7 +139,7 @@
  *   returnType (* name)
  *
  *
- * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
+ * 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
  * a function pointer type for an application callback out of
  * a return type for the callback and a name for the callback.
  * It should be used in the following fashion:
@@ -210,7 +171,7 @@
  *   returnType (* name)
  *
  *
- * 6. NULL_PTR: This macro is the value of a NULL pointer.
+ * 5. NULL_PTR: This macro is the value of a NULL pointer.
  *
  * In any ANSI/ISO C environment (and in many others as well),
  * this should best be defined by
@@ -222,7 +183,8 @@
 
 
 /* All the various Cryptoki types and #define'd values are in the
- * file pkcs11t.h. */
+ * file pkcs11t.h.
+ */
 #include "pkcs11t.h"
 
 #define __PASTE(x,y)      x##y
@@ -238,7 +200,8 @@
   extern CK_DECLARE_FUNCTION(CK_RV, name)
 
 /* pkcs11f.h has all the information about the Cryptoki
- * function prototypes. */
+ * function prototypes.
+ */
 #include "pkcs11f.h"
 
 #undef CK_NEED_ARG_LIST
@@ -257,7 +220,8 @@
   typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
 
 /* pkcs11f.h has all the information about the Cryptoki
- * function prototypes. */
+ * function prototypes.
+ */
 #include "pkcs11f.h"
 
 #undef CK_NEED_ARG_LIST
@@ -282,7 +246,8 @@
 
 /* Pile all the function pointers into the CK_FUNCTION_LIST. */
 /* pkcs11f.h has all the information about the Cryptoki
- * function prototypes. */
+ * function prototypes.
+ */
 #include "pkcs11f.h"
 
 };
@@ -296,4 +261,5 @@
 }
 #endif
 
-#endif
+#endif /* _PKCS11_H_ */
+
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h	Wed Jun 12 10:02:49 2019 +0530
@@ -1,26 +1,20 @@
-/* pkcs11f.h include file for PKCS #11. */
-/* $Revision: 1.4 $ */
-
-/* License to copy and use this software is granted provided that it is
- * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
- * (Cryptoki)" in all material mentioning or referencing this software.
-
- * License is also granted to make and use derivative works provided that
- * such works are identified as "derived from the RSA Security Inc. PKCS #11
- * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
- * referencing the derived work.
-
- * RSA Security Inc. makes no representations concerning either the
- * merchantability of this software or the suitability of this software for
- * any particular purpose. It is provided "as is" without express or implied
- * warranty of any kind.
+/* Copyright (c) OASIS Open 2016. All Rights Reserved./
+ * /Distributed under the terms of the OASIS IPR Policy,
+ * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
+ * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
  */
 
-/* This header file contains pretty much everything about all the */
-/* Cryptoki function prototypes.  Because this information is */
-/* used for more than just declaring function prototypes, the */
-/* order of the functions appearing herein is important, and */
-/* should not be altered. */
+/* Latest version of the specification:
+ * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
+ */
+
+/* This header file contains pretty much everything about all the
+ * Cryptoki function prototypes.  Because this information is
+ * used for more than just declaring function prototypes, the
+ * order of the functions appearing herein is important, and
+ * should not be altered.
+ */
 
 /* General-purpose */
 
@@ -30,13 +24,15 @@
 (
   CK_VOID_PTR   pInitArgs  /* if this is not NULL_PTR, it gets
                             * cast to CK_C_INITIALIZE_ARGS_PTR
-                            * and dereferenced */
+                            * and dereferenced
+                            */
 );
 #endif
 
 
 /* C_Finalize indicates that an application is done with the
- * Cryptoki library. */
+ * Cryptoki library.
+ */
 CK_PKCS11_FUNCTION_INFO(C_Finalize)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -59,7 +55,8 @@
 #ifdef CK_NEED_ARG_LIST
 (
   CK_FUNCTION_LIST_PTR_PTR ppFunctionList  /* receives pointer to
-                                            * function list */
+                                            * function list
+                                            */
 );
 #endif
 
@@ -71,7 +68,7 @@
 CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
 #ifdef CK_NEED_ARG_LIST
 (
-  CK_BBOOL       tokenPresent,  /* only slots with tokens? */
+  CK_BBOOL       tokenPresent,  /* only slots with tokens */
   CK_SLOT_ID_PTR pSlotList,     /* receives array of slot IDs */
   CK_ULONG_PTR   pulCount       /* receives number of slots */
 );
@@ -79,7 +76,8 @@
 
 
 /* C_GetSlotInfo obtains information about a particular slot in
- * the system. */
+ * the system.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -90,7 +88,8 @@
 
 
 /* C_GetTokenInfo obtains information about a particular token
- * in the system. */
+ * in the system.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -101,7 +100,8 @@
 
 
 /* C_GetMechanismList obtains a list of mechanism types
- * supported by a token. */
+ * supported by a token.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -113,7 +113,8 @@
 
 
 /* C_GetMechanismInfo obtains information about a particular
- * mechanism possibly supported by a token. */
+ * mechanism possibly supported by a token.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -127,7 +128,6 @@
 /* C_InitToken initializes a token. */
 CK_PKCS11_FUNCTION_INFO(C_InitToken)
 #ifdef CK_NEED_ARG_LIST
-/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */
 (
   CK_SLOT_ID      slotID,    /* ID of the token's slot */
   CK_UTF8CHAR_PTR pPin,      /* the SO's initial PIN */
@@ -165,7 +165,8 @@
 /* Session management */
 
 /* C_OpenSession opens a session between an application and a
- * token. */
+ * token.
+ */
 CK_PKCS11_FUNCTION_INFO(C_OpenSession)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -179,7 +180,8 @@
 
 
 /* C_CloseSession closes a session between an application and a
- * token. */
+ * token.
+ */
 CK_PKCS11_FUNCTION_INFO(C_CloseSession)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -208,7 +210,8 @@
 
 
 /* C_GetOperationState obtains the state of the cryptographic operation
- * in a session. */
+ * in a session.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -220,7 +223,8 @@
 
 
 /* C_SetOperationState restores the state of the cryptographic
- * operation in a session. */
+ * operation in a session.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SetOperationState)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -270,7 +274,8 @@
 
 
 /* C_CopyObject copies an object, creating a new object for the
- * copy. */
+ * copy.
+ */
 CK_PKCS11_FUNCTION_INFO(C_CopyObject)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -305,7 +310,8 @@
 
 
 /* C_GetAttributeValue obtains the value of one or more object
- * attributes. */
+ * attributes.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -318,7 +324,8 @@
 
 
 /* C_SetAttributeValue modifies the value of one or more object
- * attributes */
+ * attributes.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -331,7 +338,8 @@
 
 
 /* C_FindObjectsInit initializes a search for token and session
- * objects that match a template. */
+ * objects that match a template.
+ */
 CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -344,7 +352,8 @@
 
 /* C_FindObjects continues a search for token and session
  * objects that match a template, obtaining additional object
- * handles. */
+ * handles.
+ */
 CK_PKCS11_FUNCTION_INFO(C_FindObjects)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -357,7 +366,8 @@
 
 
 /* C_FindObjectsFinal finishes a search for token and session
- * objects. */
+ * objects.
+ */
 CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -394,7 +404,8 @@
 
 
 /* C_EncryptUpdate continues a multiple-part encryption
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -408,7 +419,8 @@
 
 
 /* C_EncryptFinal finishes a multiple-part encryption
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_EncryptFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -444,7 +456,8 @@
 
 
 /* C_DecryptUpdate continues a multiple-part decryption
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -458,7 +471,8 @@
 
 
 /* C_DecryptFinal finishes a multiple-part decryption
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DecryptFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -496,7 +510,8 @@
 
 
 /* C_DigestUpdate continues a multiple-part message-digesting
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -509,7 +524,8 @@
 
 /* C_DigestKey continues a multi-part message-digesting
  * operation, by digesting the value of a secret key as part of
- * the data already digested. */
+ * the data already digested.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DigestKey)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -520,7 +536,8 @@
 
 
 /* C_DigestFinal finishes a multiple-part message-digesting
- * operation. */
+ * operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -537,7 +554,8 @@
 /* C_SignInit initializes a signature (private key encryption)
  * operation, where the signature is (will be) an appendix to
  * the data, and plaintext cannot be recovered from the
- *signature. */
+ * signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignInit)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -550,7 +568,8 @@
 
 /* C_Sign signs (encrypts with private key) data in a single
  * part, where the signature is (will be) an appendix to the
- * data, and plaintext cannot be recovered from the signature. */
+ * data, and plaintext cannot be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_Sign)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -565,7 +584,8 @@
 
 /* C_SignUpdate continues a multiple-part signature operation,
  * where the signature is (will be) an appendix to the data,
- * and plaintext cannot be recovered from the signature. */
+ * and plaintext cannot be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -577,7 +597,8 @@
 
 
 /* C_SignFinal finishes a multiple-part signature operation,
- * returning the signature. */
+ * returning the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -589,7 +610,8 @@
 
 
 /* C_SignRecoverInit initializes a signature operation, where
- * the data can be recovered from the signature. */
+ * the data can be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -601,7 +623,8 @@
 
 
 /* C_SignRecover signs data in a single operation, where the
- * data can be recovered from the signature. */
+ * data can be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignRecover)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -619,7 +642,8 @@
 
 /* C_VerifyInit initializes a verification operation, where the
  * signature is an appendix to the data, and plaintext cannot
- *  cannot be recovered from the signature (e.g. DSA). */
+ * cannot be recovered from the signature (e.g. DSA).
+ */
 CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -632,7 +656,8 @@
 
 /* C_Verify verifies a signature in a single-part operation,
  * where the signature is an appendix to the data, and plaintext
- * cannot be recovered from the signature. */
+ * cannot be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_Verify)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -647,7 +672,8 @@
 
 /* C_VerifyUpdate continues a multiple-part verification
  * operation, where the signature is an appendix to the data,
- * and plaintext cannot be recovered from the signature. */
+ * and plaintext cannot be recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -659,7 +685,8 @@
 
 
 /* C_VerifyFinal finishes a multiple-part verification
- * operation, checking the signature. */
+ * operation, checking the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -671,7 +698,8 @@
 
 
 /* C_VerifyRecoverInit initializes a signature verification
- * operation, where the data is recovered from the signature. */
+ * operation, where the data is recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -683,7 +711,8 @@
 
 
 /* C_VerifyRecover verifies a signature in a single-part
- * operation, where the data is recovered from the signature. */
+ * operation, where the data is recovered from the signature.
+ */
 CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -700,7 +729,8 @@
 /* Dual-function cryptographic operations */
 
 /* C_DigestEncryptUpdate continues a multiple-part digesting
- * and encryption operation. */
+ * and encryption operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -714,7 +744,8 @@
 
 
 /* C_DecryptDigestUpdate continues a multiple-part decryption and
- * digesting operation. */
+ * digesting operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -728,7 +759,8 @@
 
 
 /* C_SignEncryptUpdate continues a multiple-part signing and
- * encryption operation. */
+ * encryption operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -742,7 +774,8 @@
 
 
 /* C_DecryptVerifyUpdate continues a multiple-part decryption and
- * verify operation. */
+ * verify operation.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -759,7 +792,8 @@
 /* Key management */
 
 /* C_GenerateKey generates a secret key, creating a new key
- * object. */
+ * object.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -773,30 +807,19 @@
 
 
 /* C_GenerateKeyPair generates a public-key/private-key pair,
- * creating new key objects. */
+ * creating new key objects.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair)
 #ifdef CK_NEED_ARG_LIST
 (
-  CK_SESSION_HANDLE    hSession,                    /* session
-                                                     * handle */
-  CK_MECHANISM_PTR     pMechanism,                  /* key-gen
-                                                     * mech. */
-  CK_ATTRIBUTE_PTR     pPublicKeyTemplate,          /* template
-                                                     * for pub.
-                                                     * key */
-  CK_ULONG             ulPublicKeyAttributeCount,   /* # pub.
-                                                     * attrs. */
-  CK_ATTRIBUTE_PTR     pPrivateKeyTemplate,         /* template
-                                                     * for priv.
-                                                     * key */
-  CK_ULONG             ulPrivateKeyAttributeCount,  /* # priv.
-                                                     * attrs. */
-  CK_OBJECT_HANDLE_PTR phPublicKey,                 /* gets pub.
-                                                     * key
-                                                     * handle */
-  CK_OBJECT_HANDLE_PTR phPrivateKey                 /* gets
-                                                     * priv. key
-                                                     * handle */
+  CK_SESSION_HANDLE    hSession,                    /* session handle */
+  CK_MECHANISM_PTR     pMechanism,                  /* key-gen mech. */
+  CK_ATTRIBUTE_PTR     pPublicKeyTemplate,          /* template for pub. key */
+  CK_ULONG             ulPublicKeyAttributeCount,   /* # pub. attrs. */
+  CK_ATTRIBUTE_PTR     pPrivateKeyTemplate,         /* template for priv. key */
+  CK_ULONG             ulPrivateKeyAttributeCount,  /* # priv.  attrs. */
+  CK_OBJECT_HANDLE_PTR phPublicKey,                 /* gets pub. key handle */
+  CK_OBJECT_HANDLE_PTR phPrivateKey                 /* gets priv. key handle */
 );
 #endif
 
@@ -816,7 +839,8 @@
 
 
 /* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
- * key object. */
+ * key object.
+ */
 CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -833,7 +857,8 @@
 
 
 /* C_DeriveKey derives a key from a base key, creating a new key
- * object. */
+ * object.
+ */
 CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -851,7 +876,8 @@
 /* Random number generation */
 
 /* C_SeedRandom mixes additional seed material into the token's
- * random number generator. */
+ * random number generator.
+ */
 CK_PKCS11_FUNCTION_INFO(C_SeedRandom)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -878,7 +904,8 @@
 
 /* C_GetFunctionStatus is a legacy function; it obtains an
  * updated status of a function running in parallel with an
- * application. */
+ * application.
+ */
 CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -888,7 +915,8 @@
 
 
 /* C_CancelFunction is a legacy function; it cancels a function
- * running in parallel. */
+ * running in parallel.
+ */
 CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -897,11 +925,9 @@
 #endif
 
 
-
-/* Functions added in for Cryptoki Version 2.01 or later */
-
 /* C_WaitForSlotEvent waits for a slot event (token insertion,
- * removal, etc.) to occur. */
+ * removal, etc.) to occur.
+ */
 CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
 #ifdef CK_NEED_ARG_LIST
 (
@@ -910,3 +936,4 @@
   CK_VOID_PTR pRserved   /* reserved.  Should be NULL_PTR */
 );
 #endif
+
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h	Wed Jun 12 10:02:49 2019 +0530
@@ -1,36 +1,33 @@
-/* pkcs11t.h include file for PKCS #11. */
-/* $Revision: 1.6 $ */
-
-/* License to copy and use this software is granted provided that it is
- * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
- * (Cryptoki)" in all material mentioning or referencing this software.
+/* Copyright (c) OASIS Open 2016. All Rights Reserved./
+ * /Distributed under the terms of the OASIS IPR Policy,
+ * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
+ * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
+ */
 
- * License is also granted to make and use derivative works provided that
- * such works are identified as "derived from the RSA Security Inc. PKCS #11
- * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
- * referencing the derived work.
-
- * RSA Security Inc. makes no representations concerning either the
- * merchantability of this software or the suitability of this software for
- * any particular purpose. It is provided "as is" without express or implied
- * warranty of any kind.
+/* Latest version of the specification:
+ * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
  */
 
 /* See top of pkcs11.h for information about the macros that
  * must be defined and the structure-packing conventions that
- * must be set before including this file. */
+ * must be set before including this file.
+ */
 
 #ifndef _PKCS11T_H_
 #define _PKCS11T_H_ 1
 
-#define CK_TRUE 1
-#define CK_FALSE 0
+#define CRYPTOKI_VERSION_MAJOR          2
+#define CRYPTOKI_VERSION_MINOR          40
+#define CRYPTOKI_VERSION_AMENDMENT      0
+
+#define CK_TRUE         1
+#define CK_FALSE        0
 
 #ifndef CK_DISABLE_TRUE_FALSE
 #ifndef FALSE
 #define FALSE CK_FALSE
 #endif
-
 #ifndef TRUE
 #define TRUE CK_TRUE
 #endif
@@ -52,7 +49,6 @@
 typedef unsigned long int CK_ULONG;
 
 /* a signed value, the same size as a CK_ULONG */
-/* CK_LONG is new for v2.0 */
 typedef long int          CK_LONG;
 
 /* at least 32 bits; each bit is a Boolean flag */
@@ -60,8 +56,8 @@
 
 
 /* some special values for certain CK_ULONG variables */
-#define CK_UNAVAILABLE_INFORMATION (~0UL)
-#define CK_EFFECTIVELY_INFINITE    0
+#define CK_UNAVAILABLE_INFORMATION      (~0UL)
+#define CK_EFFECTIVELY_INFINITE         0UL
 
 
 typedef CK_BYTE     CK_PTR   CK_BYTE_PTR;
@@ -74,9 +70,10 @@
 typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR;
 
 
-/* The following value is always invalid if used as a session */
-/* handle or object handle */
-#define CK_INVALID_HANDLE 0
+/* The following value is always invalid if used as a session
+ * handle or object handle
+ */
+#define CK_INVALID_HANDLE       0UL
 
 
 typedef struct CK_VERSION {
@@ -88,13 +85,9 @@
 
 
 typedef struct CK_INFO {
-  /* manufacturerID and libraryDecription have been changed from
-   * CK_CHAR to CK_UTF8CHAR for v2.10 */
   CK_VERSION    cryptokiVersion;     /* Cryptoki interface ver */
   CK_UTF8CHAR   manufacturerID[32];  /* blank padded */
   CK_FLAGS      flags;               /* must be zero */
-
-  /* libraryDescription and libraryVersion are new for v2.0 */
   CK_UTF8CHAR   libraryDescription[32];  /* blank padded */
   CK_VERSION    libraryVersion;          /* version of library */
 } CK_INFO;
@@ -103,12 +96,11 @@
 
 
 /* CK_NOTIFICATION enumerates the types of notifications that
- * Cryptoki provides to an application */
-/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG
- * for v2.0 */
+ * Cryptoki provides to an application
+ */
 typedef CK_ULONG CK_NOTIFICATION;
-#define CKN_SURRENDER       0
-
+#define CKN_SURRENDER           0UL
+#define CKN_OTP_CHANGED         1UL
 
 typedef CK_ULONG          CK_SLOT_ID;
 
@@ -117,13 +109,10 @@
 
 /* CK_SLOT_INFO provides information about a slot */
 typedef struct CK_SLOT_INFO {
-  /* slotDescription and manufacturerID have been changed from
-   * CK_CHAR to CK_UTF8CHAR for v2.10 */
   CK_UTF8CHAR   slotDescription[64];  /* blank padded */
   CK_UTF8CHAR   manufacturerID[32];   /* blank padded */
   CK_FLAGS      flags;
 
-  /* hardwareVersion and firmwareVersion are new for v2.0 */
   CK_VERSION    hardwareVersion;  /* version of hardware */
   CK_VERSION    firmwareVersion;  /* version of firmware */
 } CK_SLOT_INFO;
@@ -131,26 +120,21 @@
 /* flags: bit flags that provide capabilities of the slot
  *      Bit Flag              Mask        Meaning
  */
-#define CKF_TOKEN_PRESENT     0x00000001  /* a token is there */
-#define CKF_REMOVABLE_DEVICE  0x00000002  /* removable devices*/
-#define CKF_HW_SLOT           0x00000004  /* hardware slot */
+#define CKF_TOKEN_PRESENT     0x00000001UL  /* a token is there */
+#define CKF_REMOVABLE_DEVICE  0x00000002UL  /* removable devices*/
+#define CKF_HW_SLOT           0x00000004UL  /* hardware slot */
 
 typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR;
 
 
 /* CK_TOKEN_INFO provides information about a token */
 typedef struct CK_TOKEN_INFO {
-  /* label, manufacturerID, and model have been changed from
-   * CK_CHAR to CK_UTF8CHAR for v2.10 */
   CK_UTF8CHAR   label[32];           /* blank padded */
   CK_UTF8CHAR   manufacturerID[32];  /* blank padded */
   CK_UTF8CHAR   model[16];           /* blank padded */
   CK_CHAR       serialNumber[16];    /* blank padded */
   CK_FLAGS      flags;               /* see below */
 
-  /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount,
-   * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been
-   * changed from CK_USHORT to CK_ULONG for v2.0 */
   CK_ULONG      ulMaxSessionCount;     /* max open sessions */
   CK_ULONG      ulSessionCount;        /* sess. now open */
   CK_ULONG      ulMaxRwSessionCount;   /* max R/W sessions */
@@ -161,9 +145,6 @@
   CK_ULONG      ulFreePublicMemory;    /* in bytes */
   CK_ULONG      ulTotalPrivateMemory;  /* in bytes */
   CK_ULONG      ulFreePrivateMemory;   /* in bytes */
-
-  /* hardwareVersion, firmwareVersion, and time are new for
-   * v2.0 */
   CK_VERSION    hardwareVersion;       /* version of hardware */
   CK_VERSION    firmwareVersion;       /* version of firmware */
   CK_CHAR       utcTime[16];           /* time */
@@ -172,146 +153,149 @@
 /* The flags parameter is defined as follows:
  *      Bit Flag                    Mask        Meaning
  */
-#define CKF_RNG                     0x00000001  /* has random #
-                                                 * generator */
-#define CKF_WRITE_PROTECTED         0x00000002  /* token is
-                                                 * write-
-                                                 * protected */
-#define CKF_LOGIN_REQUIRED          0x00000004  /* user must
-                                                 * login */
-#define CKF_USER_PIN_INITIALIZED    0x00000008  /* normal user's
-                                                 * PIN is set */
+#define CKF_RNG                     0x00000001UL  /* has random # generator */
+#define CKF_WRITE_PROTECTED         0x00000002UL  /* token is write-protected */
+#define CKF_LOGIN_REQUIRED          0x00000004UL  /* user must login */
+#define CKF_USER_PIN_INITIALIZED    0x00000008UL  /* normal user's PIN is set */
 
-/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0.  If it is set,
+/* CKF_RESTORE_KEY_NOT_NEEDED.  If it is set,
  * that means that *every* time the state of cryptographic
  * operations of a session is successfully saved, all keys
- * needed to continue those operations are stored in the state */
-#define CKF_RESTORE_KEY_NOT_NEEDED  0x00000020
+ * needed to continue those operations are stored in the state
+ */
+#define CKF_RESTORE_KEY_NOT_NEEDED  0x00000020UL
 
-/* CKF_CLOCK_ON_TOKEN is new for v2.0.  If it is set, that means
+/* CKF_CLOCK_ON_TOKEN.  If it is set, that means
  * that the token has some sort of clock.  The time on that
- * clock is returned in the token info structure */
-#define CKF_CLOCK_ON_TOKEN          0x00000040
+ * clock is returned in the token info structure
+ */
+#define CKF_CLOCK_ON_TOKEN          0x00000040UL
 
-/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0.  If it is
+/* CKF_PROTECTED_AUTHENTICATION_PATH.  If it is
  * set, that means that there is some way for the user to login
- * without sending a PIN through the Cryptoki library itself */
-#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100
+ * without sending a PIN through the Cryptoki library itself
+ */
+#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100UL
 
-/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0.  If it is true,
+/* CKF_DUAL_CRYPTO_OPERATIONS.  If it is true,
  * that means that a single session with the token can perform
  * dual simultaneous cryptographic operations (digest and
  * encrypt; decrypt and digest; sign and encrypt; and decrypt
- * and sign) */
-#define CKF_DUAL_CRYPTO_OPERATIONS  0x00000200
+ * and sign)
+ */
+#define CKF_DUAL_CRYPTO_OPERATIONS  0x00000200UL
 
-/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the
+/* CKF_TOKEN_INITIALIZED. If it is true, the
  * token has been initialized using C_InitializeToken or an
  * equivalent mechanism outside the scope of PKCS #11.
  * Calling C_InitializeToken when this flag is set will cause
- * the token to be reinitialized. */
-#define CKF_TOKEN_INITIALIZED       0x00000400
+ * the token to be reinitialized.
+ */
+#define CKF_TOKEN_INITIALIZED       0x00000400UL
 
-/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is
+/* CKF_SECONDARY_AUTHENTICATION. If it is
  * true, the token supports secondary authentication for
- * private key objects. This flag is deprecated in v2.11 and
-   onwards. */
-#define CKF_SECONDARY_AUTHENTICATION  0x00000800
+ * private key objects.
+ */
+#define CKF_SECONDARY_AUTHENTICATION  0x00000800UL
 
-/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an
+/* CKF_USER_PIN_COUNT_LOW. If it is true, an
  * incorrect user login PIN has been entered at least once
- * since the last successful authentication. */
-#define CKF_USER_PIN_COUNT_LOW       0x00010000
-
-/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true,
- * supplying an incorrect user PIN will it to become locked. */
-#define CKF_USER_PIN_FINAL_TRY       0x00020000
+ * since the last successful authentication.
+ */
+#define CKF_USER_PIN_COUNT_LOW       0x00010000UL
 
-/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the
+/* CKF_USER_PIN_FINAL_TRY. If it is true,
+ * supplying an incorrect user PIN will it to become locked.
+ */
+#define CKF_USER_PIN_FINAL_TRY       0x00020000UL
+
+/* CKF_USER_PIN_LOCKED. If it is true, the
  * user PIN has been locked. User login to the token is not
- * possible. */
-#define CKF_USER_PIN_LOCKED          0x00040000
+ * possible.
+ */
+#define CKF_USER_PIN_LOCKED          0x00040000UL
 
-/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+/* CKF_USER_PIN_TO_BE_CHANGED. If it is true,
  * the user PIN value is the default value set by token
  * initialization or manufacturing, or the PIN has been
- * expired by the card. */
-#define CKF_USER_PIN_TO_BE_CHANGED   0x00080000
+ * expired by the card.
+ */
+#define CKF_USER_PIN_TO_BE_CHANGED   0x00080000UL
 
-/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an
+/* CKF_SO_PIN_COUNT_LOW. If it is true, an
  * incorrect SO login PIN has been entered at least once since
- * the last successful authentication. */
-#define CKF_SO_PIN_COUNT_LOW         0x00100000
+ * the last successful authentication.
+ */
+#define CKF_SO_PIN_COUNT_LOW         0x00100000UL
 
-/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true,
- * supplying an incorrect SO PIN will it to become locked. */
-#define CKF_SO_PIN_FINAL_TRY         0x00200000
+/* CKF_SO_PIN_FINAL_TRY. If it is true,
+ * supplying an incorrect SO PIN will it to become locked.
+ */
+#define CKF_SO_PIN_FINAL_TRY         0x00200000UL
 
-/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO
+/* CKF_SO_PIN_LOCKED. If it is true, the SO
  * PIN has been locked. SO login to the token is not possible.
  */
-#define CKF_SO_PIN_LOCKED            0x00400000
+#define CKF_SO_PIN_LOCKED            0x00400000UL
 
-/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+/* CKF_SO_PIN_TO_BE_CHANGED. If it is true,
  * the SO PIN value is the default value set by token
  * initialization or manufacturing, or the PIN has been
- * expired by the card. */
-#define CKF_SO_PIN_TO_BE_CHANGED     0x00800000
+ * expired by the card.
+ */
+#define CKF_SO_PIN_TO_BE_CHANGED     0x00800000UL
+
+#define CKF_ERROR_STATE              0x01000000UL
 
 typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR;
 
 
 /* CK_SESSION_HANDLE is a Cryptoki-assigned value that
- * identifies a session */
+ * identifies a session
+ */
 typedef CK_ULONG          CK_SESSION_HANDLE;
 
 typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR;
 
 
 /* CK_USER_TYPE enumerates the types of Cryptoki users */
-/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for
- * v2.0 */
 typedef CK_ULONG          CK_USER_TYPE;
 /* Security Officer */
-#define CKU_SO    0
+#define CKU_SO                  0UL
 /* Normal user */
-#define CKU_USER  1
-/* Context specific (added in v2.20) */
-#define CKU_CONTEXT_SPECIFIC   2
+#define CKU_USER                1UL
+/* Context specific */
+#define CKU_CONTEXT_SPECIFIC    2UL
 
 /* CK_STATE enumerates the session states */
-/* CK_STATE has been changed from an enum to a CK_ULONG for
- * v2.0 */
 typedef CK_ULONG          CK_STATE;
-#define CKS_RO_PUBLIC_SESSION  0
-#define CKS_RO_USER_FUNCTIONS  1
-#define CKS_RW_PUBLIC_SESSION  2
-#define CKS_RW_USER_FUNCTIONS  3
-#define CKS_RW_SO_FUNCTIONS    4
-
+#define CKS_RO_PUBLIC_SESSION   0UL
+#define CKS_RO_USER_FUNCTIONS   1UL
+#define CKS_RW_PUBLIC_SESSION   2UL
+#define CKS_RW_USER_FUNCTIONS   3UL
+#define CKS_RW_SO_FUNCTIONS     4UL
 
 /* CK_SESSION_INFO provides information about a session */
 typedef struct CK_SESSION_INFO {
   CK_SLOT_ID    slotID;
   CK_STATE      state;
   CK_FLAGS      flags;          /* see below */
-
-  /* ulDeviceError was changed from CK_USHORT to CK_ULONG for
-   * v2.0 */
   CK_ULONG      ulDeviceError;  /* device-dependent error code */
 } CK_SESSION_INFO;
 
 /* The flags are defined in the following table:
  *      Bit Flag                Mask        Meaning
  */
-#define CKF_RW_SESSION          0x00000002  /* session is r/w */
-#define CKF_SERIAL_SESSION      0x00000004  /* no parallel */
+#define CKF_RW_SESSION          0x00000002UL /* session is r/w */
+#define CKF_SERIAL_SESSION      0x00000004UL /* no parallel    */
 
 typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR;
 
 
 /* CK_OBJECT_HANDLE is a token-specific identifier for an
- * object  */
+ * object
+ */
 typedef CK_ULONG          CK_OBJECT_HANDLE;
 
 typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR;
@@ -319,251 +303,273 @@
 
 /* CK_OBJECT_CLASS is a value that identifies the classes (or
  * types) of objects that Cryptoki recognizes.  It is defined
- * as follows: */
-/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for
- * v2.0 */
+ * as follows:
+ */
 typedef CK_ULONG          CK_OBJECT_CLASS;
 
 /* The following classes of objects are defined: */
-/* CKO_HW_FEATURE is new for v2.10 */
-/* CKO_DOMAIN_PARAMETERS is new for v2.11 */
-/* CKO_MECHANISM is new for v2.20 */
-#define CKO_DATA              0x00000000
-#define CKO_CERTIFICATE       0x00000001
-#define CKO_PUBLIC_KEY        0x00000002
-#define CKO_PRIVATE_KEY       0x00000003
-#define CKO_SECRET_KEY        0x00000004
-#define CKO_HW_FEATURE        0x00000005
-#define CKO_DOMAIN_PARAMETERS 0x00000006
-#define CKO_MECHANISM         0x00000007
-#define CKO_VENDOR_DEFINED    0x80000000
+#define CKO_DATA              0x00000000UL
+#define CKO_CERTIFICATE       0x00000001UL
+#define CKO_PUBLIC_KEY        0x00000002UL
+#define CKO_PRIVATE_KEY       0x00000003UL
+#define CKO_SECRET_KEY        0x00000004UL
+#define CKO_HW_FEATURE        0x00000005UL
+#define CKO_DOMAIN_PARAMETERS 0x00000006UL
+#define CKO_MECHANISM         0x00000007UL
+#define CKO_OTP_KEY           0x00000008UL
+
+#define CKO_VENDOR_DEFINED    0x80000000UL
 
 typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR;
 
-/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a
- * value that identifies the hardware feature type of an object
- * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */
+/* CK_HW_FEATURE_TYPE is a value that identifies the hardware feature type
+ * of an object with CK_OBJECT_CLASS equal to CKO_HW_FEATURE.
+ */
 typedef CK_ULONG          CK_HW_FEATURE_TYPE;
 
 /* The following hardware feature types are defined */
-/* CKH_USER_INTERFACE is new for v2.20 */
-#define CKH_MONOTONIC_COUNTER  0x00000001
-#define CKH_CLOCK           0x00000002
-#define CKH_USER_INTERFACE  0x00000003
-#define CKH_VENDOR_DEFINED  0x80000000
+#define CKH_MONOTONIC_COUNTER  0x00000001UL
+#define CKH_CLOCK              0x00000002UL
+#define CKH_USER_INTERFACE     0x00000003UL
+#define CKH_VENDOR_DEFINED     0x80000000UL
 
 /* CK_KEY_TYPE is a value that identifies a key type */
-/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */
 typedef CK_ULONG          CK_KEY_TYPE;
 
 /* the following key types are defined: */
-#define CKK_RSA             0x00000000
-#define CKK_DSA             0x00000001
-#define CKK_DH              0x00000002
-
-/* CKK_ECDSA and CKK_KEA are new for v2.0 */
-/* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */
-#define CKK_ECDSA           0x00000003
-#define CKK_EC              0x00000003
-#define CKK_X9_42_DH        0x00000004
-#define CKK_KEA             0x00000005
-
-#define CKK_GENERIC_SECRET  0x00000010
-#define CKK_RC2             0x00000011
-#define CKK_RC4             0x00000012
-#define CKK_DES             0x00000013
-#define CKK_DES2            0x00000014
-#define CKK_DES3            0x00000015
+#define CKK_RSA                 0x00000000UL
+#define CKK_DSA                 0x00000001UL
+#define CKK_DH                  0x00000002UL
+#define CKK_ECDSA               0x00000003UL /* Deprecated */
+#define CKK_EC                  0x00000003UL
+#define CKK_X9_42_DH            0x00000004UL
+#define CKK_KEA                 0x00000005UL
+#define CKK_GENERIC_SECRET      0x00000010UL
+#define CKK_RC2                 0x00000011UL
+#define CKK_RC4                 0x00000012UL
+#define CKK_DES                 0x00000013UL
+#define CKK_DES2                0x00000014UL
+#define CKK_DES3                0x00000015UL
+#define CKK_CAST                0x00000016UL
+#define CKK_CAST3               0x00000017UL
+#define CKK_CAST5               0x00000018UL /* Deprecated */
+#define CKK_CAST128             0x00000018UL
+#define CKK_RC5                 0x00000019UL
+#define CKK_IDEA                0x0000001AUL
+#define CKK_SKIPJACK            0x0000001BUL
+#define CKK_BATON               0x0000001CUL
+#define CKK_JUNIPER             0x0000001DUL
+#define CKK_CDMF                0x0000001EUL
+#define CKK_AES                 0x0000001FUL
+#define CKK_BLOWFISH            0x00000020UL
+#define CKK_TWOFISH             0x00000021UL
+#define CKK_SECURID             0x00000022UL
+#define CKK_HOTP                0x00000023UL
+#define CKK_ACTI                0x00000024UL
+#define CKK_CAMELLIA            0x00000025UL
+#define CKK_ARIA                0x00000026UL
 
-/* all these key types are new for v2.0 */
-#define CKK_CAST            0x00000016
-#define CKK_CAST3           0x00000017
-/* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */
-#define CKK_CAST5           0x00000018
-#define CKK_CAST128         0x00000018
-#define CKK_RC5             0x00000019
-#define CKK_IDEA            0x0000001A
-#define CKK_SKIPJACK        0x0000001B
-#define CKK_BATON           0x0000001C
-#define CKK_JUNIPER         0x0000001D
-#define CKK_CDMF            0x0000001E
-#define CKK_AES             0x0000001F
+#define CKK_MD5_HMAC            0x00000027UL
+#define CKK_SHA_1_HMAC          0x00000028UL
+#define CKK_RIPEMD128_HMAC      0x00000029UL
+#define CKK_RIPEMD160_HMAC      0x0000002AUL
+#define CKK_SHA256_HMAC         0x0000002BUL
+#define CKK_SHA384_HMAC         0x0000002CUL
+#define CKK_SHA512_HMAC         0x0000002DUL
+#define CKK_SHA224_HMAC         0x0000002EUL
 
-/* BlowFish and TwoFish are new for v2.20 */
-#define CKK_BLOWFISH        0x00000020
-#define CKK_TWOFISH         0x00000021
+#define CKK_SEED                0x0000002FUL
+#define CKK_GOSTR3410           0x00000030UL
+#define CKK_GOSTR3411           0x00000031UL
+#define CKK_GOST28147           0x00000032UL
 
-#define CKK_VENDOR_DEFINED  0x80000000
+
+
+#define CKK_VENDOR_DEFINED      0x80000000UL
 
 
 /* CK_CERTIFICATE_TYPE is a value that identifies a certificate
- * type */
-/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG
- * for v2.0 */
+ * type
+ */
 typedef CK_ULONG          CK_CERTIFICATE_TYPE;
 
+#define CK_CERTIFICATE_CATEGORY_UNSPECIFIED     0UL
+#define CK_CERTIFICATE_CATEGORY_TOKEN_USER      1UL
+#define CK_CERTIFICATE_CATEGORY_AUTHORITY       2UL
+#define CK_CERTIFICATE_CATEGORY_OTHER_ENTITY    3UL
+
+#define CK_SECURITY_DOMAIN_UNSPECIFIED     0UL
+#define CK_SECURITY_DOMAIN_MANUFACTURER    1UL
+#define CK_SECURITY_DOMAIN_OPERATOR        2UL
+#define CK_SECURITY_DOMAIN_THIRD_PARTY     3UL
+
+
 /* The following certificate types are defined: */
-/* CKC_X_509_ATTR_CERT is new for v2.10 */
-/* CKC_WTLS is new for v2.20 */
-#define CKC_X_509           0x00000000
-#define CKC_X_509_ATTR_CERT 0x00000001
-#define CKC_WTLS            0x00000002
-#define CKC_VENDOR_DEFINED  0x80000000
+#define CKC_X_509               0x00000000UL
+#define CKC_X_509_ATTR_CERT     0x00000001UL
+#define CKC_WTLS                0x00000002UL
+#define CKC_VENDOR_DEFINED      0x80000000UL
 
 
 /* CK_ATTRIBUTE_TYPE is a value that identifies an attribute
- * type */
-/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for
- * v2.0 */
+ * type
+ */
 typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 
 /* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which
-   consists of an array of values. */
-#define CKF_ARRAY_ATTRIBUTE    0x40000000
+ * consists of an array of values.
+ */
+#define CKF_ARRAY_ATTRIBUTE     0x40000000UL
+
+/* The following OTP-related defines relate to the CKA_OTP_FORMAT attribute */
+#define CK_OTP_FORMAT_DECIMAL           0UL
+#define CK_OTP_FORMAT_HEXADECIMAL       1UL
+#define CK_OTP_FORMAT_ALPHANUMERIC      2UL
+#define CK_OTP_FORMAT_BINARY            3UL
+
+/* The following OTP-related defines relate to the CKA_OTP_..._REQUIREMENT
+ * attributes
+ */
+#define CK_OTP_PARAM_IGNORED            0UL
+#define CK_OTP_PARAM_OPTIONAL           1UL
+#define CK_OTP_PARAM_MANDATORY          2UL
 
 /* The following attribute types are defined: */
-#define CKA_CLASS              0x00000000
-#define CKA_TOKEN              0x00000001
-#define CKA_PRIVATE            0x00000002
-#define CKA_LABEL              0x00000003
-#define CKA_APPLICATION        0x00000010
-#define CKA_VALUE              0x00000011
-
-/* CKA_OBJECT_ID is new for v2.10 */
-#define CKA_OBJECT_ID          0x00000012
-
-#define CKA_CERTIFICATE_TYPE   0x00000080
-#define CKA_ISSUER             0x00000081
-#define CKA_SERIAL_NUMBER      0x00000082
-
-/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new
- * for v2.10 */
-#define CKA_AC_ISSUER          0x00000083
-#define CKA_OWNER              0x00000084
-#define CKA_ATTR_TYPES         0x00000085
-
-/* CKA_TRUSTED is new for v2.11 */
-#define CKA_TRUSTED            0x00000086
-
-/* CKA_CERTIFICATE_CATEGORY ...
- * CKA_CHECK_VALUE are new for v2.20 */
-#define CKA_CERTIFICATE_CATEGORY        0x00000087
-#define CKA_JAVA_MIDP_SECURITY_DOMAIN   0x00000088
-#define CKA_URL                         0x00000089
-#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008A
-#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008B
-#define CKA_CHECK_VALUE                 0x00000090
+#define CKA_CLASS              0x00000000UL
+#define CKA_TOKEN              0x00000001UL
+#define CKA_PRIVATE            0x00000002UL
+#define CKA_LABEL              0x00000003UL
+#define CKA_APPLICATION        0x00000010UL
+#define CKA_VALUE              0x00000011UL
+#define CKA_OBJECT_ID          0x00000012UL
+#define CKA_CERTIFICATE_TYPE   0x00000080UL
+#define CKA_ISSUER             0x00000081UL
+#define CKA_SERIAL_NUMBER      0x00000082UL
+#define CKA_AC_ISSUER          0x00000083UL
+#define CKA_OWNER              0x00000084UL
+#define CKA_ATTR_TYPES         0x00000085UL
+#define CKA_TRUSTED            0x00000086UL
+#define CKA_CERTIFICATE_CATEGORY        0x00000087UL
+#define CKA_JAVA_MIDP_SECURITY_DOMAIN   0x00000088UL
+#define CKA_URL                         0x00000089UL
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008AUL
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008BUL
+#define CKA_NAME_HASH_ALGORITHM         0x0000008CUL
+#define CKA_CHECK_VALUE                 0x00000090UL
 
-#define CKA_KEY_TYPE           0x00000100
-#define CKA_SUBJECT            0x00000101
-#define CKA_ID                 0x00000102
-#define CKA_SENSITIVE          0x00000103
-#define CKA_ENCRYPT            0x00000104
-#define CKA_DECRYPT            0x00000105
-#define CKA_WRAP               0x00000106
-#define CKA_UNWRAP             0x00000107
-#define CKA_SIGN               0x00000108
-#define CKA_SIGN_RECOVER       0x00000109
-#define CKA_VERIFY             0x0000010A
-#define CKA_VERIFY_RECOVER     0x0000010B
-#define CKA_DERIVE             0x0000010C
-#define CKA_START_DATE         0x00000110
-#define CKA_END_DATE           0x00000111
-#define CKA_MODULUS            0x00000120
-#define CKA_MODULUS_BITS       0x00000121
-#define CKA_PUBLIC_EXPONENT    0x00000122
-#define CKA_PRIVATE_EXPONENT   0x00000123
-#define CKA_PRIME_1            0x00000124
-#define CKA_PRIME_2            0x00000125
-#define CKA_EXPONENT_1         0x00000126
-#define CKA_EXPONENT_2         0x00000127
-#define CKA_COEFFICIENT        0x00000128
-#define CKA_PRIME              0x00000130
-#define CKA_SUBPRIME           0x00000131
-#define CKA_BASE               0x00000132
+#define CKA_KEY_TYPE           0x00000100UL
+#define CKA_SUBJECT            0x00000101UL
+#define CKA_ID                 0x00000102UL
+#define CKA_SENSITIVE          0x00000103UL
+#define CKA_ENCRYPT            0x00000104UL
+#define CKA_DECRYPT            0x00000105UL
+#define CKA_WRAP               0x00000106UL
+#define CKA_UNWRAP             0x00000107UL
+#define CKA_SIGN               0x00000108UL
+#define CKA_SIGN_RECOVER       0x00000109UL
+#define CKA_VERIFY             0x0000010AUL
+#define CKA_VERIFY_RECOVER     0x0000010BUL
+#define CKA_DERIVE             0x0000010CUL
+#define CKA_START_DATE         0x00000110UL
+#define CKA_END_DATE           0x00000111UL
+#define CKA_MODULUS            0x00000120UL
+#define CKA_MODULUS_BITS       0x00000121UL
+#define CKA_PUBLIC_EXPONENT    0x00000122UL
+#define CKA_PRIVATE_EXPONENT   0x00000123UL
+#define CKA_PRIME_1            0x00000124UL
+#define CKA_PRIME_2            0x00000125UL
+#define CKA_EXPONENT_1         0x00000126UL
+#define CKA_EXPONENT_2         0x00000127UL
+#define CKA_COEFFICIENT        0x00000128UL
+#define CKA_PUBLIC_KEY_INFO    0x00000129UL
+#define CKA_PRIME              0x00000130UL
+#define CKA_SUBPRIME           0x00000131UL
+#define CKA_BASE               0x00000132UL
 
-/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */
-#define CKA_PRIME_BITS         0x00000133
-#define CKA_SUBPRIME_BITS      0x00000134
+#define CKA_PRIME_BITS         0x00000133UL
+#define CKA_SUBPRIME_BITS      0x00000134UL
 #define CKA_SUB_PRIME_BITS     CKA_SUBPRIME_BITS
-/* (To retain backwards-compatibility) */
-
-#define CKA_VALUE_BITS         0x00000160
-#define CKA_VALUE_LEN          0x00000161
 
-/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE,
- * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS,
- * and CKA_EC_POINT are new for v2.0 */
-#define CKA_EXTRACTABLE        0x00000162
-#define CKA_LOCAL              0x00000163
-#define CKA_NEVER_EXTRACTABLE  0x00000164
-#define CKA_ALWAYS_SENSITIVE   0x00000165
+#define CKA_VALUE_BITS         0x00000160UL
+#define CKA_VALUE_LEN          0x00000161UL
+#define CKA_EXTRACTABLE        0x00000162UL
+#define CKA_LOCAL              0x00000163UL
+#define CKA_NEVER_EXTRACTABLE  0x00000164UL
+#define CKA_ALWAYS_SENSITIVE   0x00000165UL
+#define CKA_KEY_GEN_MECHANISM  0x00000166UL
+
+#define CKA_MODIFIABLE         0x00000170UL
+#define CKA_COPYABLE           0x00000171UL
+
+#define CKA_DESTROYABLE        0x00000172UL
 
-/* CKA_KEY_GEN_MECHANISM is new for v2.11 */
-#define CKA_KEY_GEN_MECHANISM  0x00000166
+#define CKA_ECDSA_PARAMS       0x00000180UL /* Deprecated */
+#define CKA_EC_PARAMS          0x00000180UL
 
-#define CKA_MODIFIABLE         0x00000170
+#define CKA_EC_POINT           0x00000181UL
 
-/* CKA_ECDSA_PARAMS is deprecated in v2.11,
- * CKA_EC_PARAMS is preferred. */
-#define CKA_ECDSA_PARAMS       0x00000180
-#define CKA_EC_PARAMS          0x00000180
+#define CKA_SECONDARY_AUTH     0x00000200UL /* Deprecated */
+#define CKA_AUTH_PIN_FLAGS     0x00000201UL /* Deprecated */
+
+#define CKA_ALWAYS_AUTHENTICATE  0x00000202UL
 
-#define CKA_EC_POINT           0x00000181
-
-/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
- * are new for v2.10. Deprecated in v2.11 and onwards. */
-#define CKA_SECONDARY_AUTH     0x00000200
-#define CKA_AUTH_PIN_FLAGS     0x00000201
+#define CKA_WRAP_WITH_TRUSTED    0x00000210UL
+#define CKA_WRAP_TEMPLATE        (CKF_ARRAY_ATTRIBUTE|0x00000211UL)
+#define CKA_UNWRAP_TEMPLATE      (CKF_ARRAY_ATTRIBUTE|0x00000212UL)
+#define CKA_DERIVE_TEMPLATE      (CKF_ARRAY_ATTRIBUTE|0x00000213UL)
 
-/* CKA_ALWAYS_AUTHENTICATE ...
- * CKA_UNWRAP_TEMPLATE are new for v2.20 */
-#define CKA_ALWAYS_AUTHENTICATE  0x00000202
+#define CKA_OTP_FORMAT                0x00000220UL
+#define CKA_OTP_LENGTH                0x00000221UL
+#define CKA_OTP_TIME_INTERVAL         0x00000222UL
+#define CKA_OTP_USER_FRIENDLY_MODE    0x00000223UL
+#define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224UL
+#define CKA_OTP_TIME_REQUIREMENT      0x00000225UL
+#define CKA_OTP_COUNTER_REQUIREMENT   0x00000226UL
+#define CKA_OTP_PIN_REQUIREMENT       0x00000227UL
+#define CKA_OTP_COUNTER               0x0000022EUL
+#define CKA_OTP_TIME                  0x0000022FUL
+#define CKA_OTP_USER_IDENTIFIER       0x0000022AUL
+#define CKA_OTP_SERVICE_IDENTIFIER    0x0000022BUL
+#define CKA_OTP_SERVICE_LOGO          0x0000022CUL
+#define CKA_OTP_SERVICE_LOGO_TYPE     0x0000022DUL
 
-#define CKA_WRAP_WITH_TRUSTED    0x00000210
-#define CKA_WRAP_TEMPLATE        (CKF_ARRAY_ATTRIBUTE|0x00000211)
-#define CKA_UNWRAP_TEMPLATE      (CKF_ARRAY_ATTRIBUTE|0x00000212)
-
-/* CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET
- * are new for v2.10 */
-#define CKA_HW_FEATURE_TYPE    0x00000300
-#define CKA_RESET_ON_INIT      0x00000301
-#define CKA_HAS_RESET          0x00000302
+#define CKA_GOSTR3410_PARAMS            0x00000250UL
+#define CKA_GOSTR3411_PARAMS            0x00000251UL
+#define CKA_GOST28147_PARAMS            0x00000252UL
 
-/* The following attributes are new for v2.20 */
-#define CKA_PIXEL_X                     0x00000400
-#define CKA_PIXEL_Y                     0x00000401
-#define CKA_RESOLUTION                  0x00000402
-#define CKA_CHAR_ROWS                   0x00000403
-#define CKA_CHAR_COLUMNS                0x00000404
-#define CKA_COLOR                       0x00000405
-#define CKA_BITS_PER_PIXEL              0x00000406
-#define CKA_CHAR_SETS                   0x00000480
-#define CKA_ENCODING_METHODS            0x00000481
-#define CKA_MIME_TYPES                  0x00000482
-#define CKA_MECHANISM_TYPE              0x00000500
-#define CKA_REQUIRED_CMS_ATTRIBUTES     0x00000501
-#define CKA_DEFAULT_CMS_ATTRIBUTES      0x00000502
-#define CKA_SUPPORTED_CMS_ATTRIBUTES    0x00000503
-#define CKA_ALLOWED_MECHANISMS          (CKF_ARRAY_ATTRIBUTE|0x00000600)
+#define CKA_HW_FEATURE_TYPE             0x00000300UL
+#define CKA_RESET_ON_INIT               0x00000301UL
+#define CKA_HAS_RESET                   0x00000302UL
 
-#define CKA_VENDOR_DEFINED     0x80000000
-#define CKA_NETSCAPE_DB        0xD5A0DB00
+#define CKA_PIXEL_X                     0x00000400UL
+#define CKA_PIXEL_Y                     0x00000401UL
+#define CKA_RESOLUTION                  0x00000402UL
+#define CKA_CHAR_ROWS                   0x00000403UL
+#define CKA_CHAR_COLUMNS                0x00000404UL
+#define CKA_COLOR                       0x00000405UL
+#define CKA_BITS_PER_PIXEL              0x00000406UL
+#define CKA_CHAR_SETS                   0x00000480UL
+#define CKA_ENCODING_METHODS            0x00000481UL
+#define CKA_MIME_TYPES                  0x00000482UL
+#define CKA_MECHANISM_TYPE              0x00000500UL
+#define CKA_REQUIRED_CMS_ATTRIBUTES     0x00000501UL
+#define CKA_DEFAULT_CMS_ATTRIBUTES      0x00000502UL
+#define CKA_SUPPORTED_CMS_ATTRIBUTES    0x00000503UL
+#define CKA_ALLOWED_MECHANISMS          (CKF_ARRAY_ATTRIBUTE|0x00000600UL)
 
+#define CKA_VENDOR_DEFINED              0x80000000UL
 
 /* CK_ATTRIBUTE is a structure that includes the type, length
- * and value of an attribute */
+ * and value of an attribute
+ */
 typedef struct CK_ATTRIBUTE {
   CK_ATTRIBUTE_TYPE type;
   CK_VOID_PTR       pValue;
-
-  /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */
   CK_ULONG          ulValueLen;  /* in bytes */
 } CK_ATTRIBUTE;
 
 typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR;
 
-
 /* CK_DATE is a structure that defines a date */
 typedef struct CK_DATE{
   CK_CHAR       year[4];   /* the year ("1900" - "9999") */
@@ -573,341 +579,411 @@
 
 
 /* CK_MECHANISM_TYPE is a value that identifies a mechanism
- * type */
-/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for
- * v2.0 */
+ * type
+ */
 typedef CK_ULONG          CK_MECHANISM_TYPE;
 
 /* the following mechanism types are defined: */
-#define CKM_RSA_PKCS_KEY_PAIR_GEN      0x00000000
-#define CKM_RSA_PKCS                   0x00000001
-#define CKM_RSA_9796                   0x00000002
-#define CKM_RSA_X_509                  0x00000003
+#define CKM_RSA_PKCS_KEY_PAIR_GEN      0x00000000UL
+#define CKM_RSA_PKCS                   0x00000001UL
+#define CKM_RSA_9796                   0x00000002UL
+#define CKM_RSA_X_509                  0x00000003UL
 
-/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS
- * are new for v2.0.  They are mechanisms which hash and sign */
-#define CKM_MD2_RSA_PKCS               0x00000004
-#define CKM_MD5_RSA_PKCS               0x00000005
-#define CKM_SHA1_RSA_PKCS              0x00000006
+#define CKM_MD2_RSA_PKCS               0x00000004UL
+#define CKM_MD5_RSA_PKCS               0x00000005UL
+#define CKM_SHA1_RSA_PKCS              0x00000006UL
+
+#define CKM_RIPEMD128_RSA_PKCS         0x00000007UL
+#define CKM_RIPEMD160_RSA_PKCS         0x00000008UL
+#define CKM_RSA_PKCS_OAEP              0x00000009UL
 
-/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and
- * CKM_RSA_PKCS_OAEP are new for v2.10 */
-#define CKM_RIPEMD128_RSA_PKCS         0x00000007
-#define CKM_RIPEMD160_RSA_PKCS         0x00000008
-#define CKM_RSA_PKCS_OAEP              0x00000009
+#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000AUL
+#define CKM_RSA_X9_31                  0x0000000BUL
+#define CKM_SHA1_RSA_X9_31             0x0000000CUL
+#define CKM_RSA_PKCS_PSS               0x0000000DUL
+#define CKM_SHA1_RSA_PKCS_PSS          0x0000000EUL
 
-/* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31,
- * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */
-#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000A
-#define CKM_RSA_X9_31                  0x0000000B
-#define CKM_SHA1_RSA_X9_31             0x0000000C
-#define CKM_RSA_PKCS_PSS               0x0000000D
-#define CKM_SHA1_RSA_PKCS_PSS          0x0000000E
+#define CKM_DSA_KEY_PAIR_GEN           0x00000010UL
+#define CKM_DSA                        0x00000011UL
+#define CKM_DSA_SHA1                   0x00000012UL
+#define CKM_DSA_SHA224                 0x00000013UL
+#define CKM_DSA_SHA256                 0x00000014UL
+#define CKM_DSA_SHA384                 0x00000015UL
+#define CKM_DSA_SHA512                 0x00000016UL
 
-#define CKM_DSA_KEY_PAIR_GEN           0x00000010
-#define CKM_DSA                        0x00000011
-#define CKM_DSA_SHA1                   0x00000012
-#define CKM_DH_PKCS_KEY_PAIR_GEN       0x00000020
-#define CKM_DH_PKCS_DERIVE             0x00000021
+#define CKM_DH_PKCS_KEY_PAIR_GEN       0x00000020UL
+#define CKM_DH_PKCS_DERIVE             0x00000021UL
+
+#define CKM_X9_42_DH_KEY_PAIR_GEN      0x00000030UL
+#define CKM_X9_42_DH_DERIVE            0x00000031UL
+#define CKM_X9_42_DH_HYBRID_DERIVE     0x00000032UL
+#define CKM_X9_42_MQV_DERIVE           0x00000033UL
 
-/* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE,
- * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for
- * v2.11 */
-#define CKM_X9_42_DH_KEY_PAIR_GEN      0x00000030
-#define CKM_X9_42_DH_DERIVE            0x00000031
-#define CKM_X9_42_DH_HYBRID_DERIVE     0x00000032
-#define CKM_X9_42_MQV_DERIVE           0x00000033
+#define CKM_SHA256_RSA_PKCS            0x00000040UL
+#define CKM_SHA384_RSA_PKCS            0x00000041UL
+#define CKM_SHA512_RSA_PKCS            0x00000042UL
+#define CKM_SHA256_RSA_PKCS_PSS        0x00000043UL
+#define CKM_SHA384_RSA_PKCS_PSS        0x00000044UL
+#define CKM_SHA512_RSA_PKCS_PSS        0x00000045UL
 
-/* CKM_SHA256/384/512 are new for v2.20 */
-#define CKM_SHA256_RSA_PKCS            0x00000040
-#define CKM_SHA384_RSA_PKCS            0x00000041
-#define CKM_SHA512_RSA_PKCS            0x00000042
-#define CKM_SHA256_RSA_PKCS_PSS        0x00000043
-#define CKM_SHA384_RSA_PKCS_PSS        0x00000044
-#define CKM_SHA512_RSA_PKCS_PSS        0x00000045
+#define CKM_SHA224_RSA_PKCS            0x00000046UL
+#define CKM_SHA224_RSA_PKCS_PSS        0x00000047UL
+
+#define CKM_SHA512_224                 0x00000048UL
+#define CKM_SHA512_224_HMAC            0x00000049UL
+#define CKM_SHA512_224_HMAC_GENERAL    0x0000004AUL
+#define CKM_SHA512_224_KEY_DERIVATION  0x0000004BUL
+#define CKM_SHA512_256                 0x0000004CUL
+#define CKM_SHA512_256_HMAC            0x0000004DUL
+#define CKM_SHA512_256_HMAC_GENERAL    0x0000004EUL
+#define CKM_SHA512_256_KEY_DERIVATION  0x0000004FUL
 
-#define CKM_RC2_KEY_GEN                0x00000100
-#define CKM_RC2_ECB                    0x00000101
-#define CKM_RC2_CBC                    0x00000102
-#define CKM_RC2_MAC                    0x00000103
+#define CKM_SHA512_T                   0x00000050UL
+#define CKM_SHA512_T_HMAC              0x00000051UL
+#define CKM_SHA512_T_HMAC_GENERAL      0x00000052UL
+#define CKM_SHA512_T_KEY_DERIVATION    0x00000053UL
+
+#define CKM_RC2_KEY_GEN                0x00000100UL
+#define CKM_RC2_ECB                    0x00000101UL
+#define CKM_RC2_CBC                    0x00000102UL
+#define CKM_RC2_MAC                    0x00000103UL
 
-/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */
-#define CKM_RC2_MAC_GENERAL            0x00000104
-#define CKM_RC2_CBC_PAD                0x00000105
+#define CKM_RC2_MAC_GENERAL            0x00000104UL
+#define CKM_RC2_CBC_PAD                0x00000105UL
 
-#define CKM_RC4_KEY_GEN                0x00000110
-#define CKM_RC4                        0x00000111
-#define CKM_DES_KEY_GEN                0x00000120
-#define CKM_DES_ECB                    0x00000121
-#define CKM_DES_CBC                    0x00000122
-#define CKM_DES_MAC                    0x00000123
+#define CKM_RC4_KEY_GEN                0x00000110UL
+#define CKM_RC4                        0x00000111UL
+#define CKM_DES_KEY_GEN                0x00000120UL
+#define CKM_DES_ECB                    0x00000121UL
+#define CKM_DES_CBC                    0x00000122UL
+#define CKM_DES_MAC                    0x00000123UL
 
-/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */
-#define CKM_DES_MAC_GENERAL            0x00000124
-#define CKM_DES_CBC_PAD                0x00000125
+#define CKM_DES_MAC_GENERAL            0x00000124UL
+#define CKM_DES_CBC_PAD                0x00000125UL
 
-#define CKM_DES2_KEY_GEN               0x00000130
-#define CKM_DES3_KEY_GEN               0x00000131
-#define CKM_DES3_ECB                   0x00000132
-#define CKM_DES3_CBC                   0x00000133
-#define CKM_DES3_MAC                   0x00000134
+#define CKM_DES2_KEY_GEN               0x00000130UL
+#define CKM_DES3_KEY_GEN               0x00000131UL
+#define CKM_DES3_ECB                   0x00000132UL
+#define CKM_DES3_CBC                   0x00000133UL
+#define CKM_DES3_MAC                   0x00000134UL
 
-/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,
- * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,
- * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */
-#define CKM_DES3_MAC_GENERAL           0x00000135
-#define CKM_DES3_CBC_PAD               0x00000136
-#define CKM_CDMF_KEY_GEN               0x00000140
-#define CKM_CDMF_ECB                   0x00000141
-#define CKM_CDMF_CBC                   0x00000142
-#define CKM_CDMF_MAC                   0x00000143
-#define CKM_CDMF_MAC_GENERAL           0x00000144
-#define CKM_CDMF_CBC_PAD               0x00000145
+#define CKM_DES3_MAC_GENERAL           0x00000135UL
+#define CKM_DES3_CBC_PAD               0x00000136UL
+#define CKM_DES3_CMAC_GENERAL          0x00000137UL
+#define CKM_DES3_CMAC                  0x00000138UL
+#define CKM_CDMF_KEY_GEN               0x00000140UL
+#define CKM_CDMF_ECB                   0x00000141UL
+#define CKM_CDMF_CBC                   0x00000142UL
+#define CKM_CDMF_MAC                   0x00000143UL
+#define CKM_CDMF_MAC_GENERAL           0x00000144UL
+#define CKM_CDMF_CBC_PAD               0x00000145UL
 
-/* the following four DES mechanisms are new for v2.20 */
-#define CKM_DES_OFB64                  0x00000150
-#define CKM_DES_OFB8                   0x00000151
-#define CKM_DES_CFB64                  0x00000152
-#define CKM_DES_CFB8                   0x00000153
+#define CKM_DES_OFB64                  0x00000150UL
+#define CKM_DES_OFB8                   0x00000151UL
+#define CKM_DES_CFB64                  0x00000152UL
+#define CKM_DES_CFB8                   0x00000153UL
+
+#define CKM_MD2                        0x00000200UL
 
-#define CKM_MD2                        0x00000200
+#define CKM_MD2_HMAC                   0x00000201UL
+#define CKM_MD2_HMAC_GENERAL           0x00000202UL
+
+#define CKM_MD5                        0x00000210UL
 
-/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */
-#define CKM_MD2_HMAC                   0x00000201
-#define CKM_MD2_HMAC_GENERAL           0x00000202
+#define CKM_MD5_HMAC                   0x00000211UL
+#define CKM_MD5_HMAC_GENERAL           0x00000212UL
+
+#define CKM_SHA_1                      0x00000220UL
 
-#define CKM_MD5                        0x00000210
-
-/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */
-#define CKM_MD5_HMAC                   0x00000211
-#define CKM_MD5_HMAC_GENERAL           0x00000212
+#define CKM_SHA_1_HMAC                 0x00000221UL
+#define CKM_SHA_1_HMAC_GENERAL         0x00000222UL
 
-#define CKM_SHA_1                      0x00000220
-
-/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */
-#define CKM_SHA_1_HMAC                 0x00000221
-#define CKM_SHA_1_HMAC_GENERAL         0x00000222
+#define CKM_RIPEMD128                  0x00000230UL
+#define CKM_RIPEMD128_HMAC             0x00000231UL
+#define CKM_RIPEMD128_HMAC_GENERAL     0x00000232UL
+#define CKM_RIPEMD160                  0x00000240UL
+#define CKM_RIPEMD160_HMAC             0x00000241UL
+#define CKM_RIPEMD160_HMAC_GENERAL     0x00000242UL
 
-/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC,
- * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,
- * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */
-#define CKM_RIPEMD128                  0x00000230
-#define CKM_RIPEMD128_HMAC             0x00000231
-#define CKM_RIPEMD128_HMAC_GENERAL     0x00000232
-#define CKM_RIPEMD160                  0x00000240
-#define CKM_RIPEMD160_HMAC             0x00000241
-#define CKM_RIPEMD160_HMAC_GENERAL     0x00000242
+#define CKM_SHA256                     0x00000250UL
+#define CKM_SHA256_HMAC                0x00000251UL
+#define CKM_SHA256_HMAC_GENERAL        0x00000252UL
+#define CKM_SHA224                     0x00000255UL
+#define CKM_SHA224_HMAC                0x00000256UL
+#define CKM_SHA224_HMAC_GENERAL        0x00000257UL
+#define CKM_SHA384                     0x00000260UL
+#define CKM_SHA384_HMAC                0x00000261UL
+#define CKM_SHA384_HMAC_GENERAL        0x00000262UL
+#define CKM_SHA512                     0x00000270UL
+#define CKM_SHA512_HMAC                0x00000271UL
+#define CKM_SHA512_HMAC_GENERAL        0x00000272UL
+#define CKM_SECURID_KEY_GEN            0x00000280UL
+#define CKM_SECURID                    0x00000282UL
+#define CKM_HOTP_KEY_GEN               0x00000290UL
+#define CKM_HOTP                       0x00000291UL
+#define CKM_ACTI                       0x000002A0UL
+#define CKM_ACTI_KEY_GEN               0x000002A1UL
 
-/* CKM_SHA256/384/512 are new for v2.20 */
-#define CKM_SHA256                     0x00000250
-#define CKM_SHA256_HMAC                0x00000251
-#define CKM_SHA256_HMAC_GENERAL        0x00000252
-#define CKM_SHA384                     0x00000260
-#define CKM_SHA384_HMAC                0x00000261
-#define CKM_SHA384_HMAC_GENERAL        0x00000262
-#define CKM_SHA512                     0x00000270
-#define CKM_SHA512_HMAC                0x00000271
-#define CKM_SHA512_HMAC_GENERAL        0x00000272
-
-/* All of the following mechanisms are new for v2.0 */
+#define CKM_CAST_KEY_GEN               0x00000300UL
+#define CKM_CAST_ECB                   0x00000301UL
+#define CKM_CAST_CBC                   0x00000302UL
+#define CKM_CAST_MAC                   0x00000303UL
+#define CKM_CAST_MAC_GENERAL           0x00000304UL
+#define CKM_CAST_CBC_PAD               0x00000305UL
+#define CKM_CAST3_KEY_GEN              0x00000310UL
+#define CKM_CAST3_ECB                  0x00000311UL
+#define CKM_CAST3_CBC                  0x00000312UL
+#define CKM_CAST3_MAC                  0x00000313UL
+#define CKM_CAST3_MAC_GENERAL          0x00000314UL
+#define CKM_CAST3_CBC_PAD              0x00000315UL
 /* Note that CAST128 and CAST5 are the same algorithm */
-#define CKM_CAST_KEY_GEN               0x00000300
-#define CKM_CAST_ECB                   0x00000301
-#define CKM_CAST_CBC                   0x00000302
-#define CKM_CAST_MAC                   0x00000303
-#define CKM_CAST_MAC_GENERAL           0x00000304
-#define CKM_CAST_CBC_PAD               0x00000305
-#define CKM_CAST3_KEY_GEN              0x00000310
-#define CKM_CAST3_ECB                  0x00000311
-#define CKM_CAST3_CBC                  0x00000312
-#define CKM_CAST3_MAC                  0x00000313
-#define CKM_CAST3_MAC_GENERAL          0x00000314
-#define CKM_CAST3_CBC_PAD              0x00000315
-#define CKM_CAST5_KEY_GEN              0x00000320
-#define CKM_CAST128_KEY_GEN            0x00000320
-#define CKM_CAST5_ECB                  0x00000321
-#define CKM_CAST128_ECB                0x00000321
-#define CKM_CAST5_CBC                  0x00000322
-#define CKM_CAST128_CBC                0x00000322
-#define CKM_CAST5_MAC                  0x00000323
-#define CKM_CAST128_MAC                0x00000323
-#define CKM_CAST5_MAC_GENERAL          0x00000324
-#define CKM_CAST128_MAC_GENERAL        0x00000324
-#define CKM_CAST5_CBC_PAD              0x00000325
-#define CKM_CAST128_CBC_PAD            0x00000325
-#define CKM_RC5_KEY_GEN                0x00000330
-#define CKM_RC5_ECB                    0x00000331
-#define CKM_RC5_CBC                    0x00000332
-#define CKM_RC5_MAC                    0x00000333
-#define CKM_RC5_MAC_GENERAL            0x00000334
-#define CKM_RC5_CBC_PAD                0x00000335
-#define CKM_IDEA_KEY_GEN               0x00000340
-#define CKM_IDEA_ECB                   0x00000341
-#define CKM_IDEA_CBC                   0x00000342
-#define CKM_IDEA_MAC                   0x00000343
-#define CKM_IDEA_MAC_GENERAL           0x00000344
-#define CKM_IDEA_CBC_PAD               0x00000345
-#define CKM_GENERIC_SECRET_KEY_GEN     0x00000350
-#define CKM_CONCATENATE_BASE_AND_KEY   0x00000360
-#define CKM_CONCATENATE_BASE_AND_DATA  0x00000362
-#define CKM_CONCATENATE_DATA_AND_BASE  0x00000363
-#define CKM_XOR_BASE_AND_DATA          0x00000364
-#define CKM_EXTRACT_KEY_FROM_KEY       0x00000365
-#define CKM_SSL3_PRE_MASTER_KEY_GEN    0x00000370
-#define CKM_SSL3_MASTER_KEY_DERIVE     0x00000371
-#define CKM_SSL3_KEY_AND_MAC_DERIVE    0x00000372
+#define CKM_CAST5_KEY_GEN              0x00000320UL
+#define CKM_CAST128_KEY_GEN            0x00000320UL
+#define CKM_CAST5_ECB                  0x00000321UL
+#define CKM_CAST128_ECB                0x00000321UL
+#define CKM_CAST5_CBC                  0x00000322UL /* Deprecated */
+#define CKM_CAST128_CBC                0x00000322UL
+#define CKM_CAST5_MAC                  0x00000323UL /* Deprecated */
+#define CKM_CAST128_MAC                0x00000323UL
+#define CKM_CAST5_MAC_GENERAL          0x00000324UL /* Deprecated */
+#define CKM_CAST128_MAC_GENERAL        0x00000324UL
+#define CKM_CAST5_CBC_PAD              0x00000325UL /* Deprecated */
+#define CKM_CAST128_CBC_PAD            0x00000325UL
+#define CKM_RC5_KEY_GEN                0x00000330UL
+#define CKM_RC5_ECB                    0x00000331UL
+#define CKM_RC5_CBC                    0x00000332UL
+#define CKM_RC5_MAC                    0x00000333UL
+#define CKM_RC5_MAC_GENERAL            0x00000334UL
+#define CKM_RC5_CBC_PAD                0x00000335UL
+#define CKM_IDEA_KEY_GEN               0x00000340UL
+#define CKM_IDEA_ECB                   0x00000341UL
+#define CKM_IDEA_CBC                   0x00000342UL
+#define CKM_IDEA_MAC                   0x00000343UL
+#define CKM_IDEA_MAC_GENERAL           0x00000344UL
+#define CKM_IDEA_CBC_PAD               0x00000345UL
+#define CKM_GENERIC_SECRET_KEY_GEN     0x00000350UL
+#define CKM_CONCATENATE_BASE_AND_KEY   0x00000360UL
+#define CKM_CONCATENATE_BASE_AND_DATA  0x00000362UL
+#define CKM_CONCATENATE_DATA_AND_BASE  0x00000363UL
+#define CKM_XOR_BASE_AND_DATA          0x00000364UL
+#define CKM_EXTRACT_KEY_FROM_KEY       0x00000365UL
+#define CKM_SSL3_PRE_MASTER_KEY_GEN    0x00000370UL
+#define CKM_SSL3_MASTER_KEY_DERIVE     0x00000371UL
+#define CKM_SSL3_KEY_AND_MAC_DERIVE    0x00000372UL
+
+#define CKM_SSL3_MASTER_KEY_DERIVE_DH  0x00000373UL
+#define CKM_TLS_PRE_MASTER_KEY_GEN     0x00000374UL
+#define CKM_TLS_MASTER_KEY_DERIVE      0x00000375UL
+#define CKM_TLS_KEY_AND_MAC_DERIVE     0x00000376UL
+#define CKM_TLS_MASTER_KEY_DERIVE_DH   0x00000377UL
+
+#define CKM_TLS_PRF                    0x00000378UL
+
+#define CKM_SSL3_MD5_MAC               0x00000380UL
+#define CKM_SSL3_SHA1_MAC              0x00000381UL
+#define CKM_MD5_KEY_DERIVATION         0x00000390UL
+#define CKM_MD2_KEY_DERIVATION         0x00000391UL
+#define CKM_SHA1_KEY_DERIVATION        0x00000392UL
+
+#define CKM_SHA256_KEY_DERIVATION      0x00000393UL
+#define CKM_SHA384_KEY_DERIVATION      0x00000394UL
+#define CKM_SHA512_KEY_DERIVATION      0x00000395UL
+#define CKM_SHA224_KEY_DERIVATION      0x00000396UL
 
-/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,
- * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and
- * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */
-#define CKM_SSL3_MASTER_KEY_DERIVE_DH  0x00000373
-#define CKM_TLS_PRE_MASTER_KEY_GEN     0x00000374
-#define CKM_TLS_MASTER_KEY_DERIVE      0x00000375
-#define CKM_TLS_KEY_AND_MAC_DERIVE     0x00000376
-#define CKM_TLS_MASTER_KEY_DERIVE_DH   0x00000377
+#define CKM_PBE_MD2_DES_CBC            0x000003A0UL
+#define CKM_PBE_MD5_DES_CBC            0x000003A1UL
+#define CKM_PBE_MD5_CAST_CBC           0x000003A2UL
+#define CKM_PBE_MD5_CAST3_CBC          0x000003A3UL
+#define CKM_PBE_MD5_CAST5_CBC          0x000003A4UL /* Deprecated */
+#define CKM_PBE_MD5_CAST128_CBC        0x000003A4UL
+#define CKM_PBE_SHA1_CAST5_CBC         0x000003A5UL /* Deprecated */
+#define CKM_PBE_SHA1_CAST128_CBC       0x000003A5UL
+#define CKM_PBE_SHA1_RC4_128           0x000003A6UL
+#define CKM_PBE_SHA1_RC4_40            0x000003A7UL
+#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003A8UL
+#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003A9UL
+#define CKM_PBE_SHA1_RC2_128_CBC       0x000003AAUL
+#define CKM_PBE_SHA1_RC2_40_CBC        0x000003ABUL
 
-/* CKM_TLS_PRF is new for v2.20 */
-#define CKM_TLS_PRF                    0x00000378
+#define CKM_PKCS5_PBKD2                0x000003B0UL
+
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003C0UL
 
-#define CKM_SSL3_MD5_MAC               0x00000380
-#define CKM_SSL3_SHA1_MAC              0x00000381
-#define CKM_MD5_KEY_DERIVATION         0x00000390
-#define CKM_MD2_KEY_DERIVATION         0x00000391
-#define CKM_SHA1_KEY_DERIVATION        0x00000392
+#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003D0UL
+#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003D1UL
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003D2UL
+#define CKM_WTLS_PRF                        0x000003D3UL
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4UL
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5UL
 
-/* CKM_SHA256/384/512 are new for v2.20 */
-#define CKM_SHA256_KEY_DERIVATION      0x00000393
-#define CKM_SHA384_KEY_DERIVATION      0x00000394
-#define CKM_SHA512_KEY_DERIVATION      0x00000395
+#define CKM_TLS10_MAC_SERVER                0x000003D6UL
+#define CKM_TLS10_MAC_CLIENT                0x000003D7UL
+#define CKM_TLS12_MAC                       0x000003D8UL
+#define CKM_TLS12_KDF                       0x000003D9UL
+#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003E0UL
+#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003E1UL
+#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003E2UL
+#define CKM_TLS12_KEY_SAFE_DERIVE           0x000003E3UL
+#define CKM_TLS_MAC                         0x000003E4UL
+#define CKM_TLS_KDF                         0x000003E5UL
+
+#define CKM_KEY_WRAP_LYNKS             0x00000400UL
+#define CKM_KEY_WRAP_SET_OAEP          0x00000401UL
+
+#define CKM_CMS_SIG                    0x00000500UL
+#define CKM_KIP_DERIVE                 0x00000510UL
+#define CKM_KIP_WRAP                   0x00000511UL
+#define CKM_KIP_MAC                    0x00000512UL
 
-#define CKM_PBE_MD2_DES_CBC            0x000003A0
-#define CKM_PBE_MD5_DES_CBC            0x000003A1
-#define CKM_PBE_MD5_CAST_CBC           0x000003A2
-#define CKM_PBE_MD5_CAST3_CBC          0x000003A3
-#define CKM_PBE_MD5_CAST5_CBC          0x000003A4
-#define CKM_PBE_MD5_CAST128_CBC        0x000003A4
-#define CKM_PBE_SHA1_CAST5_CBC         0x000003A5
-#define CKM_PBE_SHA1_CAST128_CBC       0x000003A5
-#define CKM_PBE_SHA1_RC4_128           0x000003A6
-#define CKM_PBE_SHA1_RC4_40            0x000003A7
-#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003A8
-#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003A9
-#define CKM_PBE_SHA1_RC2_128_CBC       0x000003AA
-#define CKM_PBE_SHA1_RC2_40_CBC        0x000003AB
+#define CKM_CAMELLIA_KEY_GEN           0x00000550UL
+#define CKM_CAMELLIA_ECB               0x00000551UL
+#define CKM_CAMELLIA_CBC               0x00000552UL
+#define CKM_CAMELLIA_MAC               0x00000553UL
+#define CKM_CAMELLIA_MAC_GENERAL       0x00000554UL
+#define CKM_CAMELLIA_CBC_PAD           0x00000555UL
+#define CKM_CAMELLIA_ECB_ENCRYPT_DATA  0x00000556UL
+#define CKM_CAMELLIA_CBC_ENCRYPT_DATA  0x00000557UL
+#define CKM_CAMELLIA_CTR               0x00000558UL
 
-/* CKM_PKCS5_PBKD2 is new for v2.10 */
-#define CKM_PKCS5_PBKD2                0x000003B0
-
-#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003C0
+#define CKM_ARIA_KEY_GEN               0x00000560UL
+#define CKM_ARIA_ECB                   0x00000561UL
+#define CKM_ARIA_CBC                   0x00000562UL
+#define CKM_ARIA_MAC                   0x00000563UL
+#define CKM_ARIA_MAC_GENERAL           0x00000564UL
+#define CKM_ARIA_CBC_PAD               0x00000565UL
+#define CKM_ARIA_ECB_ENCRYPT_DATA      0x00000566UL
+#define CKM_ARIA_CBC_ENCRYPT_DATA      0x00000567UL
 
-/* WTLS mechanisms are new for v2.20 */
-#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003D0
-#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003D1
-#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003D2
-#define CKM_WTLS_PRF                        0x000003D3
-#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4
-#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5
-
-/* new for v2.40 */
-#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003E0
-#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003E1
-#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003E2
-#define CKM_TLS_MAC                         0x000003E4
-
-#define CKM_KEY_WRAP_LYNKS             0x00000400
-#define CKM_KEY_WRAP_SET_OAEP          0x00000401
-
-/* CKM_CMS_SIG is new for v2.20 */
-#define CKM_CMS_SIG                    0x00000500
+#define CKM_SEED_KEY_GEN               0x00000650UL
+#define CKM_SEED_ECB                   0x00000651UL
+#define CKM_SEED_CBC                   0x00000652UL
+#define CKM_SEED_MAC                   0x00000653UL
+#define CKM_SEED_MAC_GENERAL           0x00000654UL
+#define CKM_SEED_CBC_PAD               0x00000655UL
+#define CKM_SEED_ECB_ENCRYPT_DATA      0x00000656UL
+#define CKM_SEED_CBC_ENCRYPT_DATA      0x00000657UL
 
-/* Fortezza mechanisms */
-#define CKM_SKIPJACK_KEY_GEN           0x00001000
-#define CKM_SKIPJACK_ECB64             0x00001001
-#define CKM_SKIPJACK_CBC64             0x00001002
-#define CKM_SKIPJACK_OFB64             0x00001003
-#define CKM_SKIPJACK_CFB64             0x00001004
-#define CKM_SKIPJACK_CFB32             0x00001005
-#define CKM_SKIPJACK_CFB16             0x00001006
-#define CKM_SKIPJACK_CFB8              0x00001007
-#define CKM_SKIPJACK_WRAP              0x00001008
-#define CKM_SKIPJACK_PRIVATE_WRAP      0x00001009
-#define CKM_SKIPJACK_RELAYX            0x0000100a
-#define CKM_KEA_KEY_PAIR_GEN           0x00001010
-#define CKM_KEA_KEY_DERIVE             0x00001011
-#define CKM_FORTEZZA_TIMESTAMP         0x00001020
-#define CKM_BATON_KEY_GEN              0x00001030
-#define CKM_BATON_ECB128               0x00001031
-#define CKM_BATON_ECB96                0x00001032
-#define CKM_BATON_CBC128               0x00001033
-#define CKM_BATON_COUNTER              0x00001034
-#define CKM_BATON_SHUFFLE              0x00001035
-#define CKM_BATON_WRAP                 0x00001036
+#define CKM_SKIPJACK_KEY_GEN           0x00001000UL
+#define CKM_SKIPJACK_ECB64             0x00001001UL
+#define CKM_SKIPJACK_CBC64             0x00001002UL
+#define CKM_SKIPJACK_OFB64             0x00001003UL
+#define CKM_SKIPJACK_CFB64             0x00001004UL
+#define CKM_SKIPJACK_CFB32             0x00001005UL
+#define CKM_SKIPJACK_CFB16             0x00001006UL
+#define CKM_SKIPJACK_CFB8              0x00001007UL
+#define CKM_SKIPJACK_WRAP              0x00001008UL
+#define CKM_SKIPJACK_PRIVATE_WRAP      0x00001009UL
+#define CKM_SKIPJACK_RELAYX            0x0000100aUL
+#define CKM_KEA_KEY_PAIR_GEN           0x00001010UL
+#define CKM_KEA_KEY_DERIVE             0x00001011UL
+#define CKM_KEA_DERIVE                 0x00001012UL
+#define CKM_FORTEZZA_TIMESTAMP         0x00001020UL
+#define CKM_BATON_KEY_GEN              0x00001030UL
+#define CKM_BATON_ECB128               0x00001031UL
+#define CKM_BATON_ECB96                0x00001032UL
+#define CKM_BATON_CBC128               0x00001033UL
+#define CKM_BATON_COUNTER              0x00001034UL
+#define CKM_BATON_SHUFFLE              0x00001035UL
+#define CKM_BATON_WRAP                 0x00001036UL
 
-/* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,
- * CKM_EC_KEY_PAIR_GEN is preferred */
-#define CKM_ECDSA_KEY_PAIR_GEN         0x00001040
-#define CKM_EC_KEY_PAIR_GEN            0x00001040
+#define CKM_ECDSA_KEY_PAIR_GEN         0x00001040UL /* Deprecated */
+#define CKM_EC_KEY_PAIR_GEN            0x00001040UL
+
+#define CKM_ECDSA                      0x00001041UL
+#define CKM_ECDSA_SHA1                 0x00001042UL
+#define CKM_ECDSA_SHA224               0x00001043UL
+#define CKM_ECDSA_SHA256               0x00001044UL
+#define CKM_ECDSA_SHA384               0x00001045UL
+#define CKM_ECDSA_SHA512               0x00001046UL
+
+#define CKM_ECDH1_DERIVE               0x00001050UL
+#define CKM_ECDH1_COFACTOR_DERIVE      0x00001051UL
+#define CKM_ECMQV_DERIVE               0x00001052UL
+
+#define CKM_ECDH_AES_KEY_WRAP          0x00001053UL
+#define CKM_RSA_AES_KEY_WRAP           0x00001054UL
+
+#define CKM_JUNIPER_KEY_GEN            0x00001060UL
+#define CKM_JUNIPER_ECB128             0x00001061UL
+#define CKM_JUNIPER_CBC128             0x00001062UL
+#define CKM_JUNIPER_COUNTER            0x00001063UL
+#define CKM_JUNIPER_SHUFFLE            0x00001064UL
+#define CKM_JUNIPER_WRAP               0x00001065UL
+#define CKM_FASTHASH                   0x00001070UL
 
-#define CKM_ECDSA                      0x00001041
-#define CKM_ECDSA_SHA1                 0x00001042
+#define CKM_AES_KEY_GEN                0x00001080UL
+#define CKM_AES_ECB                    0x00001081UL
+#define CKM_AES_CBC                    0x00001082UL
+#define CKM_AES_MAC                    0x00001083UL
+#define CKM_AES_MAC_GENERAL            0x00001084UL
+#define CKM_AES_CBC_PAD                0x00001085UL
+#define CKM_AES_CTR                    0x00001086UL
+#define CKM_AES_GCM                    0x00001087UL
+#define CKM_AES_CCM                    0x00001088UL
+#define CKM_AES_CTS                    0x00001089UL
+#define CKM_AES_CMAC                   0x0000108AUL
+#define CKM_AES_CMAC_GENERAL           0x0000108BUL
 
-/* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE
- * are new for v2.11 */
-#define CKM_ECDH1_DERIVE               0x00001050
-#define CKM_ECDH1_COFACTOR_DERIVE      0x00001051
-#define CKM_ECMQV_DERIVE               0x00001052
+#define CKM_AES_XCBC_MAC               0x0000108CUL
+#define CKM_AES_XCBC_MAC_96            0x0000108DUL
+#define CKM_AES_GMAC                   0x0000108EUL
 
-#define CKM_JUNIPER_KEY_GEN            0x00001060
-#define CKM_JUNIPER_ECB128             0x00001061
-#define CKM_JUNIPER_CBC128             0x00001062
-#define CKM_JUNIPER_COUNTER            0x00001063
-#define CKM_JUNIPER_SHUFFLE            0x00001064
-#define CKM_JUNIPER_WRAP               0x00001065
-#define CKM_FASTHASH                   0x00001070
+#define CKM_BLOWFISH_KEY_GEN           0x00001090UL
+#define CKM_BLOWFISH_CBC               0x00001091UL
+#define CKM_TWOFISH_KEY_GEN            0x00001092UL
+#define CKM_TWOFISH_CBC                0x00001093UL
+#define CKM_BLOWFISH_CBC_PAD           0x00001094UL
+#define CKM_TWOFISH_CBC_PAD            0x00001095UL
+
+#define CKM_DES_ECB_ENCRYPT_DATA       0x00001100UL
+#define CKM_DES_CBC_ENCRYPT_DATA       0x00001101UL
+#define CKM_DES3_ECB_ENCRYPT_DATA      0x00001102UL
+#define CKM_DES3_CBC_ENCRYPT_DATA      0x00001103UL
+#define CKM_AES_ECB_ENCRYPT_DATA       0x00001104UL
+#define CKM_AES_CBC_ENCRYPT_DATA       0x00001105UL
 
-/* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,
- * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,
- * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are
- * new for v2.11 */
-#define CKM_AES_KEY_GEN                0x00001080
-#define CKM_AES_ECB                    0x00001081
-#define CKM_AES_CBC                    0x00001082
-#define CKM_AES_MAC                    0x00001083
-#define CKM_AES_MAC_GENERAL            0x00001084
-#define CKM_AES_CBC_PAD                0x00001085
+#define CKM_GOSTR3410_KEY_PAIR_GEN     0x00001200UL
+#define CKM_GOSTR3410                  0x00001201UL
+#define CKM_GOSTR3410_WITH_GOSTR3411   0x00001202UL
+#define CKM_GOSTR3410_KEY_WRAP         0x00001203UL
+#define CKM_GOSTR3410_DERIVE           0x00001204UL
+#define CKM_GOSTR3411                  0x00001210UL
+#define CKM_GOSTR3411_HMAC             0x00001211UL
+#define CKM_GOST28147_KEY_GEN          0x00001220UL
+#define CKM_GOST28147_ECB              0x00001221UL
+#define CKM_GOST28147                  0x00001222UL
+#define CKM_GOST28147_MAC              0x00001223UL
+#define CKM_GOST28147_KEY_WRAP         0x00001224UL
 
-/* BlowFish and TwoFish are new for v2.20 */
-#define CKM_BLOWFISH_KEY_GEN           0x00001090
-#define CKM_BLOWFISH_CBC               0x00001091
-#define CKM_TWOFISH_KEY_GEN            0x00001092
-#define CKM_TWOFISH_CBC                0x00001093
-
+#define CKM_DSA_PARAMETER_GEN          0x00002000UL
+#define CKM_DH_PKCS_PARAMETER_GEN      0x00002001UL
+#define CKM_X9_42_DH_PARAMETER_GEN     0x00002002UL
+#define CKM_DSA_PROBABLISTIC_PARAMETER_GEN    0x00002003UL
+#define CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN    0x00002004UL
 
-/* CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20 */
-#define CKM_DES_ECB_ENCRYPT_DATA       0x00001100
-#define CKM_DES_CBC_ENCRYPT_DATA       0x00001101
-#define CKM_DES3_ECB_ENCRYPT_DATA      0x00001102
-#define CKM_DES3_CBC_ENCRYPT_DATA      0x00001103
-#define CKM_AES_ECB_ENCRYPT_DATA       0x00001104
-#define CKM_AES_CBC_ENCRYPT_DATA       0x00001105
+#define CKM_AES_OFB                    0x00002104UL
+#define CKM_AES_CFB64                  0x00002105UL
+#define CKM_AES_CFB8                   0x00002106UL
+#define CKM_AES_CFB128                 0x00002107UL
 
-#define CKM_DSA_PARAMETER_GEN          0x00002000
-#define CKM_DH_PKCS_PARAMETER_GEN      0x00002001
-#define CKM_X9_42_DH_PARAMETER_GEN     0x00002002
+#define CKM_AES_CFB1                   0x00002108UL
+#define CKM_AES_KEY_WRAP               0x00002109UL     /* WAS: 0x00001090 */
+#define CKM_AES_KEY_WRAP_PAD           0x0000210AUL     /* WAS: 0x00001091 */
 
-#define CKM_VENDOR_DEFINED             0x80000000
+#define CKM_RSA_PKCS_TPM_1_1           0x00004001UL
+#define CKM_RSA_PKCS_OAEP_TPM_1_1      0x00004002UL
+
+#define CKM_VENDOR_DEFINED             0x80000000UL
 
 typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;
 
 
 /* CK_MECHANISM is a structure that specifies a particular
- * mechanism  */
+ * mechanism
+ */
 typedef struct CK_MECHANISM {
   CK_MECHANISM_TYPE mechanism;
   CK_VOID_PTR       pParameter;
-
-  /* ulParameterLen was changed from CK_USHORT to CK_ULONG for
-   * v2.0 */
   CK_ULONG          ulParameterLen;  /* in bytes */
 } CK_MECHANISM;
 
@@ -915,7 +991,8 @@
 
 
 /* CK_MECHANISM_INFO provides information about a particular
- * mechanism */
+ * mechanism
+ */
 typedef struct CK_MECHANISM_INFO {
     CK_ULONG    ulMinKeySize;
     CK_ULONG    ulMaxKeySize;
@@ -923,179 +1000,163 @@
 } CK_MECHANISM_INFO;
 
 /* The flags are defined as follows:
- *      Bit Flag               Mask        Meaning */
-#define CKF_HW                 0x00000001  /* performed by HW */
+ *      Bit Flag               Mask          Meaning */
+#define CKF_HW                 0x00000001UL  /* performed by HW */
 
-/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN,
- * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER,
- * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP,
- * and CKF_DERIVE are new for v2.0.  They specify whether or not
- * a mechanism can be used for a particular task */
-#define CKF_ENCRYPT            0x00000100
-#define CKF_DECRYPT            0x00000200
-#define CKF_DIGEST             0x00000400
-#define CKF_SIGN               0x00000800
-#define CKF_SIGN_RECOVER       0x00001000
-#define CKF_VERIFY             0x00002000
-#define CKF_VERIFY_RECOVER     0x00004000
-#define CKF_GENERATE           0x00008000
-#define CKF_GENERATE_KEY_PAIR  0x00010000
-#define CKF_WRAP               0x00020000
-#define CKF_UNWRAP             0x00040000
-#define CKF_DERIVE             0x00080000
+/* Specify whether or not a mechanism can be used for a particular task */
+#define CKF_ENCRYPT            0x00000100UL
+#define CKF_DECRYPT            0x00000200UL
+#define CKF_DIGEST             0x00000400UL
+#define CKF_SIGN               0x00000800UL
+#define CKF_SIGN_RECOVER       0x00001000UL
+#define CKF_VERIFY             0x00002000UL
+#define CKF_VERIFY_RECOVER     0x00004000UL
+#define CKF_GENERATE           0x00008000UL
+#define CKF_GENERATE_KEY_PAIR  0x00010000UL
+#define CKF_WRAP               0x00020000UL
+#define CKF_UNWRAP             0x00040000UL
+#define CKF_DERIVE             0x00080000UL
 
-/* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE,
- * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They
- * describe a token's EC capabilities not available in mechanism
- * information. */
-#define CKF_EC_F_P             0x00100000
-#define CKF_EC_F_2M            0x00200000
-#define CKF_EC_ECPARAMETERS    0x00400000
-#define CKF_EC_NAMEDCURVE      0x00800000
-#define CKF_EC_UNCOMPRESS      0x01000000
-#define CKF_EC_COMPRESS        0x02000000
+/* Describe a token's EC capabilities not available in mechanism
+ * information.
+ */
+#define CKF_EC_F_P             0x00100000UL
+#define CKF_EC_F_2M            0x00200000UL
+#define CKF_EC_ECPARAMETERS    0x00400000UL
+#define CKF_EC_NAMEDCURVE      0x00800000UL
+#define CKF_EC_UNCOMPRESS      0x01000000UL
+#define CKF_EC_COMPRESS        0x02000000UL
 
-#define CKF_EXTENSION          0x80000000 /* FALSE for this version */
+#define CKF_EXTENSION          0x80000000UL
 
 typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR;
 
-
 /* CK_RV is a value that identifies the return value of a
- * Cryptoki function */
-/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */
+ * Cryptoki function
+ */
 typedef CK_ULONG          CK_RV;
 
-#define CKR_OK                                0x00000000
-#define CKR_CANCEL                            0x00000001
-#define CKR_HOST_MEMORY                       0x00000002
-#define CKR_SLOT_ID_INVALID                   0x00000003
+#define CKR_OK                                0x00000000UL
+#define CKR_CANCEL                            0x00000001UL
+#define CKR_HOST_MEMORY                       0x00000002UL
+#define CKR_SLOT_ID_INVALID                   0x00000003UL
 
-/* CKR_FLAGS_INVALID was removed for v2.0 */
-
-/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */
-#define CKR_GENERAL_ERROR                     0x00000005
-#define CKR_FUNCTION_FAILED                   0x00000006
+#define CKR_GENERAL_ERROR                     0x00000005UL
+#define CKR_FUNCTION_FAILED                   0x00000006UL
 
-/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS,
- * and CKR_CANT_LOCK are new for v2.01 */
-#define CKR_ARGUMENTS_BAD                     0x00000007
-#define CKR_NO_EVENT                          0x00000008
-#define CKR_NEED_TO_CREATE_THREADS            0x00000009
-#define CKR_CANT_LOCK                         0x0000000A
+#define CKR_ARGUMENTS_BAD                     0x00000007UL
+#define CKR_NO_EVENT                          0x00000008UL
+#define CKR_NEED_TO_CREATE_THREADS            0x00000009UL
+#define CKR_CANT_LOCK                         0x0000000AUL
 
-#define CKR_ATTRIBUTE_READ_ONLY               0x00000010
-#define CKR_ATTRIBUTE_SENSITIVE               0x00000011
-#define CKR_ATTRIBUTE_TYPE_INVALID            0x00000012
-#define CKR_ATTRIBUTE_VALUE_INVALID           0x00000013
-#define CKR_DATA_INVALID                      0x00000020
-#define CKR_DATA_LEN_RANGE                    0x00000021
-#define CKR_DEVICE_ERROR                      0x00000030
-#define CKR_DEVICE_MEMORY                     0x00000031
-#define CKR_DEVICE_REMOVED                    0x00000032
-#define CKR_ENCRYPTED_DATA_INVALID            0x00000040
-#define CKR_ENCRYPTED_DATA_LEN_RANGE          0x00000041
-#define CKR_FUNCTION_CANCELED                 0x00000050
-#define CKR_FUNCTION_NOT_PARALLEL             0x00000051
+#define CKR_ATTRIBUTE_READ_ONLY               0x00000010UL
+#define CKR_ATTRIBUTE_SENSITIVE               0x00000011UL
+#define CKR_ATTRIBUTE_TYPE_INVALID            0x00000012UL
+#define CKR_ATTRIBUTE_VALUE_INVALID           0x00000013UL
+
+#define CKR_ACTION_PROHIBITED                 0x0000001BUL
 
-/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */
-#define CKR_FUNCTION_NOT_SUPPORTED            0x00000054
-
-#define CKR_KEY_HANDLE_INVALID                0x00000060
+#define CKR_DATA_INVALID                      0x00000020UL
+#define CKR_DATA_LEN_RANGE                    0x00000021UL
+#define CKR_DEVICE_ERROR                      0x00000030UL
+#define CKR_DEVICE_MEMORY                     0x00000031UL
+#define CKR_DEVICE_REMOVED                    0x00000032UL
+#define CKR_ENCRYPTED_DATA_INVALID            0x00000040UL
+#define CKR_ENCRYPTED_DATA_LEN_RANGE          0x00000041UL
+#define CKR_FUNCTION_CANCELED                 0x00000050UL
+#define CKR_FUNCTION_NOT_PARALLEL             0x00000051UL
 
-/* CKR_KEY_SENSITIVE was removed for v2.0 */
+#define CKR_FUNCTION_NOT_SUPPORTED            0x00000054UL
 
-#define CKR_KEY_SIZE_RANGE                    0x00000062
-#define CKR_KEY_TYPE_INCONSISTENT             0x00000063
+#define CKR_KEY_HANDLE_INVALID                0x00000060UL
+
+#define CKR_KEY_SIZE_RANGE                    0x00000062UL
+#define CKR_KEY_TYPE_INCONSISTENT             0x00000063UL
 
-/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED,
- * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED,
- * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for
- * v2.0 */
-#define CKR_KEY_NOT_NEEDED                    0x00000064
-#define CKR_KEY_CHANGED                       0x00000065
-#define CKR_KEY_NEEDED                        0x00000066
-#define CKR_KEY_INDIGESTIBLE                  0x00000067
-#define CKR_KEY_FUNCTION_NOT_PERMITTED        0x00000068
-#define CKR_KEY_NOT_WRAPPABLE                 0x00000069
-#define CKR_KEY_UNEXTRACTABLE                 0x0000006A
+#define CKR_KEY_NOT_NEEDED                    0x00000064UL
+#define CKR_KEY_CHANGED                       0x00000065UL
+#define CKR_KEY_NEEDED                        0x00000066UL
+#define CKR_KEY_INDIGESTIBLE                  0x00000067UL
+#define CKR_KEY_FUNCTION_NOT_PERMITTED        0x00000068UL
+#define CKR_KEY_NOT_WRAPPABLE                 0x00000069UL
+#define CKR_KEY_UNEXTRACTABLE                 0x0000006AUL
 
-#define CKR_MECHANISM_INVALID                 0x00000070
-#define CKR_MECHANISM_PARAM_INVALID           0x00000071
+#define CKR_MECHANISM_INVALID                 0x00000070UL
+#define CKR_MECHANISM_PARAM_INVALID           0x00000071UL
 
-/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID
- * were removed for v2.0 */
-#define CKR_OBJECT_HANDLE_INVALID             0x00000082
-#define CKR_OPERATION_ACTIVE                  0x00000090
-#define CKR_OPERATION_NOT_INITIALIZED         0x00000091
-#define CKR_PIN_INCORRECT                     0x000000A0
-#define CKR_PIN_INVALID                       0x000000A1
-#define CKR_PIN_LEN_RANGE                     0x000000A2
+#define CKR_OBJECT_HANDLE_INVALID             0x00000082UL
+#define CKR_OPERATION_ACTIVE                  0x00000090UL
+#define CKR_OPERATION_NOT_INITIALIZED         0x00000091UL
+#define CKR_PIN_INCORRECT                     0x000000A0UL
+#define CKR_PIN_INVALID                       0x000000A1UL
+#define CKR_PIN_LEN_RANGE                     0x000000A2UL
+
+#define CKR_PIN_EXPIRED                       0x000000A3UL
+#define CKR_PIN_LOCKED                        0x000000A4UL
 
-/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */
-#define CKR_PIN_EXPIRED                       0x000000A3
-#define CKR_PIN_LOCKED                        0x000000A4
+#define CKR_SESSION_CLOSED                    0x000000B0UL
+#define CKR_SESSION_COUNT                     0x000000B1UL
+#define CKR_SESSION_HANDLE_INVALID            0x000000B3UL
+#define CKR_SESSION_PARALLEL_NOT_SUPPORTED    0x000000B4UL
+#define CKR_SESSION_READ_ONLY                 0x000000B5UL
+#define CKR_SESSION_EXISTS                    0x000000B6UL
 
-#define CKR_SESSION_CLOSED                    0x000000B0
-#define CKR_SESSION_COUNT                     0x000000B1
-#define CKR_SESSION_HANDLE_INVALID            0x000000B3
-#define CKR_SESSION_PARALLEL_NOT_SUPPORTED    0x000000B4
-#define CKR_SESSION_READ_ONLY                 0x000000B5
-#define CKR_SESSION_EXISTS                    0x000000B6
+#define CKR_SESSION_READ_ONLY_EXISTS          0x000000B7UL
+#define CKR_SESSION_READ_WRITE_SO_EXISTS      0x000000B8UL
 
-/* CKR_SESSION_READ_ONLY_EXISTS and
- * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */
-#define CKR_SESSION_READ_ONLY_EXISTS          0x000000B7
-#define CKR_SESSION_READ_WRITE_SO_EXISTS      0x000000B8
+#define CKR_SIGNATURE_INVALID                 0x000000C0UL
+#define CKR_SIGNATURE_LEN_RANGE               0x000000C1UL
+#define CKR_TEMPLATE_INCOMPLETE               0x000000D0UL
+#define CKR_TEMPLATE_INCONSISTENT             0x000000D1UL
+#define CKR_TOKEN_NOT_PRESENT                 0x000000E0UL
+#define CKR_TOKEN_NOT_RECOGNIZED              0x000000E1UL
+#define CKR_TOKEN_WRITE_PROTECTED             0x000000E2UL
+#define CKR_UNWRAPPING_KEY_HANDLE_INVALID     0x000000F0UL
+#define CKR_UNWRAPPING_KEY_SIZE_RANGE         0x000000F1UL
+#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT  0x000000F2UL
+#define CKR_USER_ALREADY_LOGGED_IN            0x00000100UL
+#define CKR_USER_NOT_LOGGED_IN                0x00000101UL
+#define CKR_USER_PIN_NOT_INITIALIZED          0x00000102UL
+#define CKR_USER_TYPE_INVALID                 0x00000103UL
 
-#define CKR_SIGNATURE_INVALID                 0x000000C0
-#define CKR_SIGNATURE_LEN_RANGE               0x000000C1
-#define CKR_TEMPLATE_INCOMPLETE               0x000000D0
-#define CKR_TEMPLATE_INCONSISTENT             0x000000D1
-#define CKR_TOKEN_NOT_PRESENT                 0x000000E0
-#define CKR_TOKEN_NOT_RECOGNIZED              0x000000E1
-#define CKR_TOKEN_WRITE_PROTECTED             0x000000E2
-#define CKR_UNWRAPPING_KEY_HANDLE_INVALID     0x000000F0
-#define CKR_UNWRAPPING_KEY_SIZE_RANGE         0x000000F1
-#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT  0x000000F2
-#define CKR_USER_ALREADY_LOGGED_IN            0x00000100
-#define CKR_USER_NOT_LOGGED_IN                0x00000101
-#define CKR_USER_PIN_NOT_INITIALIZED          0x00000102
-#define CKR_USER_TYPE_INVALID                 0x00000103
+#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN    0x00000104UL
+#define CKR_USER_TOO_MANY_TYPES               0x00000105UL
 
-/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES
- * are new to v2.01 */
-#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN    0x00000104
-#define CKR_USER_TOO_MANY_TYPES               0x00000105
+#define CKR_WRAPPED_KEY_INVALID               0x00000110UL
+#define CKR_WRAPPED_KEY_LEN_RANGE             0x00000112UL
+#define CKR_WRAPPING_KEY_HANDLE_INVALID       0x00000113UL
+#define CKR_WRAPPING_KEY_SIZE_RANGE           0x00000114UL
+#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT    0x00000115UL
+#define CKR_RANDOM_SEED_NOT_SUPPORTED         0x00000120UL
+
+#define CKR_RANDOM_NO_RNG                     0x00000121UL
 
-#define CKR_WRAPPED_KEY_INVALID               0x00000110
-#define CKR_WRAPPED_KEY_LEN_RANGE             0x00000112
-#define CKR_WRAPPING_KEY_HANDLE_INVALID       0x00000113
-#define CKR_WRAPPING_KEY_SIZE_RANGE           0x00000114
-#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT    0x00000115
-#define CKR_RANDOM_SEED_NOT_SUPPORTED         0x00000120
+#define CKR_DOMAIN_PARAMS_INVALID             0x00000130UL
+
+#define CKR_CURVE_NOT_SUPPORTED               0x00000140UL
 
-/* These are new to v2.0 */
-#define CKR_RANDOM_NO_RNG                     0x00000121
+#define CKR_BUFFER_TOO_SMALL                  0x00000150UL
+#define CKR_SAVED_STATE_INVALID               0x00000160UL
+#define CKR_INFORMATION_SENSITIVE             0x00000170UL
+#define CKR_STATE_UNSAVEABLE                  0x00000180UL
 
-/* These are new to v2.11 */
-#define CKR_DOMAIN_PARAMS_INVALID             0x00000130
+#define CKR_CRYPTOKI_NOT_INITIALIZED          0x00000190UL
+#define CKR_CRYPTOKI_ALREADY_INITIALIZED      0x00000191UL
+#define CKR_MUTEX_BAD                         0x000001A0UL
+#define CKR_MUTEX_NOT_LOCKED                  0x000001A1UL
 
-/* These are new to v2.0 */
-#define CKR_BUFFER_TOO_SMALL                  0x00000150
-#define CKR_SAVED_STATE_INVALID               0x00000160
-#define CKR_INFORMATION_SENSITIVE             0x00000170
-#define CKR_STATE_UNSAVEABLE                  0x00000180
+#define CKR_NEW_PIN_MODE                      0x000001B0UL
+#define CKR_NEXT_OTP                          0x000001B1UL
 
-/* These are new to v2.01 */
-#define CKR_CRYPTOKI_NOT_INITIALIZED          0x00000190
-#define CKR_CRYPTOKI_ALREADY_INITIALIZED      0x00000191
-#define CKR_MUTEX_BAD                         0x000001A0
-#define CKR_MUTEX_NOT_LOCKED                  0x000001A1
+#define CKR_EXCEEDED_MAX_ITERATIONS           0x000001B5UL
+#define CKR_FIPS_SELF_TEST_FAILED             0x000001B6UL
+#define CKR_LIBRARY_LOAD_FAILED               0x000001B7UL
+#define CKR_PIN_TOO_WEAK                      0x000001B8UL
+#define CKR_PUBLIC_KEY_INVALID                0x000001B9UL
 
-/* This is new to v2.20 */
-#define CKR_FUNCTION_REJECTED                 0x00000200
+#define CKR_FUNCTION_REJECTED                 0x00000200UL
 
-#define CKR_VENDOR_DEFINED                    0x80000000
+#define CKR_VENDOR_DEFINED                    0x80000000UL
 
 
 /* CK_NOTIFY is an application callback that processes events */
@@ -1108,8 +1169,8 @@
 
 /* CK_FUNCTION_LIST is a structure holding a Cryptoki spec
  * version and pointers of appropriate types to all the
- * Cryptoki functions */
-/* CK_FUNCTION_LIST is new for v2.0 */
+ * Cryptoki functions
+ */
 typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST;
 
 typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR;
@@ -1118,14 +1179,16 @@
 
 
 /* CK_CREATEMUTEX is an application callback for creating a
- * mutex object */
+ * mutex object
+ */
 typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)(
   CK_VOID_PTR_PTR ppMutex  /* location to receive ptr to mutex */
 );
 
 
 /* CK_DESTROYMUTEX is an application callback for destroying a
- * mutex object */
+ * mutex object
+ */
 typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)(
   CK_VOID_PTR pMutex  /* pointer to mutex */
 );
@@ -1138,14 +1201,16 @@
 
 
 /* CK_UNLOCKMUTEX is an application callback for unlocking a
- * mutex */
+ * mutex
+ */
 typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)(
   CK_VOID_PTR pMutex  /* pointer to mutex */
 );
 
 
 /* CK_C_INITIALIZE_ARGS provides the optional arguments to
- * C_Initialize */
+ * C_Initialize
+ */
 typedef struct CK_C_INITIALIZE_ARGS {
   CK_CREATEMUTEX CreateMutex;
   CK_DESTROYMUTEX DestroyMutex;
@@ -1158,8 +1223,8 @@
 /* flags: bit flags that provide capabilities of the slot
  *      Bit Flag                           Mask       Meaning
  */
-#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001
-#define CKF_OS_LOCKING_OK                  0x00000002
+#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001UL
+#define CKF_OS_LOCKING_OK                  0x00000002UL
 
 typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR;
 
@@ -1169,37 +1234,36 @@
 /* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */
 #define CKF_DONT_BLOCK     1
 
-/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10.
- * CK_RSA_PKCS_OAEP_MGF_TYPE  is used to indicate the Message
+/* CK_RSA_PKCS_MGF_TYPE  is used to indicate the Message
  * Generation Function (MGF) applied to a message block when
  * formatting a message block for the PKCS #1 OAEP encryption
- * scheme. */
+ * scheme.
+ */
 typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE;
 
 typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR;
 
 /* The following MGFs are defined */
-/* CKG_MGF1_SHA256, CKG_MGF1_SHA384, and CKG_MGF1_SHA512
- * are new for v2.20 */
-#define CKG_MGF1_SHA1         0x00000001
-#define CKG_MGF1_SHA256       0x00000002
-#define CKG_MGF1_SHA384       0x00000003
-#define CKG_MGF1_SHA512       0x00000004
+#define CKG_MGF1_SHA1         0x00000001UL
+#define CKG_MGF1_SHA256       0x00000002UL
+#define CKG_MGF1_SHA384       0x00000003UL
+#define CKG_MGF1_SHA512       0x00000004UL
+#define CKG_MGF1_SHA224       0x00000005UL
 
-/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10.
- * CK_RSA_PKCS_OAEP_SOURCE_TYPE  is used to indicate the source
+/* CK_RSA_PKCS_OAEP_SOURCE_TYPE  is used to indicate the source
  * of the encoding parameter when formatting a message block
- * for the PKCS #1 OAEP encryption scheme. */
+ * for the PKCS #1 OAEP encryption scheme.
+ */
 typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE;
 
 typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR;
 
 /* The following encoding parameter sources are defined */
-#define CKZ_DATA_SPECIFIED    0x00000001
+#define CKZ_DATA_SPECIFIED    0x00000001UL
 
-/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10.
- * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the
- * CKM_RSA_PKCS_OAEP mechanism. */
+/* CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_OAEP mechanism.
+ */
 typedef struct CK_RSA_PKCS_OAEP_PARAMS {
         CK_MECHANISM_TYPE hashAlg;
         CK_RSA_PKCS_MGF_TYPE mgf;
@@ -1210,9 +1274,9 @@
 
 typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR;
 
-/* CK_RSA_PKCS_PSS_PARAMS is new for v2.11.
- * CK_RSA_PKCS_PSS_PARAMS provides the parameters to the
- * CKM_RSA_PKCS_PSS mechanism(s). */
+/* CK_RSA_PKCS_PSS_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_PSS mechanism(s).
+ */
 typedef struct CK_RSA_PKCS_PSS_PARAMS {
         CK_MECHANISM_TYPE    hashAlg;
         CK_RSA_PKCS_MGF_TYPE mgf;
@@ -1221,15 +1285,23 @@
 
 typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR;
 
-/* CK_EC_KDF_TYPE is new for v2.11. */
 typedef CK_ULONG CK_EC_KDF_TYPE;
 
 /* The following EC Key Derivation Functions are defined */
-#define CKD_NULL                 0x00000001
-#define CKD_SHA1_KDF             0x00000002
+#define CKD_NULL                 0x00000001UL
+#define CKD_SHA1_KDF             0x00000002UL
 
-/* CK_ECDH1_DERIVE_PARAMS is new for v2.11.
- * CK_ECDH1_DERIVE_PARAMS provides the parameters to the
+/* The following X9.42 DH key derivation functions are defined */
+#define CKD_SHA1_KDF_ASN1        0x00000003UL
+#define CKD_SHA1_KDF_CONCATENATE 0x00000004UL
+#define CKD_SHA224_KDF           0x00000005UL
+#define CKD_SHA256_KDF           0x00000006UL
+#define CKD_SHA384_KDF           0x00000007UL
+#define CKD_SHA512_KDF           0x00000008UL
+#define CKD_CPDIVERSIFY_KDF      0x00000009UL
+
+
+/* CK_ECDH1_DERIVE_PARAMS provides the parameters to the
  * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms,
  * where each party contributes one key pair.
  */
@@ -1243,10 +1315,10 @@
 
 typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR;
 
-
-/* CK_ECDH2_DERIVE_PARAMS is new for v2.11.
+/*
  * CK_ECDH2_DERIVE_PARAMS provides the parameters to the
- * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */
+ * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs.
+ */
 typedef struct CK_ECDH2_DERIVE_PARAMS {
   CK_EC_KDF_TYPE kdf;
   CK_ULONG ulSharedDataLen;
@@ -1277,19 +1349,15 @@
 typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR;
 
 /* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the
- * CKM_X9_42_DH_PARAMETER_GEN mechanisms (new for PKCS #11 v2.11) */
+ * CKM_X9_42_DH_PARAMETER_GEN mechanisms
+ */
 typedef CK_ULONG CK_X9_42_DH_KDF_TYPE;
 typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR;
 
-/* The following X9.42 DH key derivation functions are defined
-   (besides CKD_NULL already defined : */
-#define CKD_SHA1_KDF_ASN1        0x00000003
-#define CKD_SHA1_KDF_CONCATENATE 0x00000004
-
-/* CK_X9_42_DH1_DERIVE_PARAMS is new for v2.11.
- * CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the
+/* CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the
  * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party
- * contributes one key pair */
+ * contributes one key pair
+ */
 typedef struct CK_X9_42_DH1_DERIVE_PARAMS {
   CK_X9_42_DH_KDF_TYPE kdf;
   CK_ULONG ulOtherInfoLen;
@@ -1300,10 +1368,10 @@
 
 typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR;
 
-/* CK_X9_42_DH2_DERIVE_PARAMS is new for v2.11.
- * CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the
+/* CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the
  * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation
- * mechanisms, where each party contributes two key pairs */
+ * mechanisms, where each party contributes two key pairs
+ */
 typedef struct CK_X9_42_DH2_DERIVE_PARAMS {
   CK_X9_42_DH_KDF_TYPE kdf;
   CK_ULONG ulOtherInfoLen;
@@ -1334,8 +1402,8 @@
 typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR;
 
 /* CK_KEA_DERIVE_PARAMS provides the parameters to the
- * CKM_KEA_DERIVE mechanism */
-/* CK_KEA_DERIVE_PARAMS is new for v2.0 */
+ * CKM_KEA_DERIVE mechanism
+ */
 typedef struct CK_KEA_DERIVE_PARAMS {
   CK_BBOOL      isSender;
   CK_ULONG      ulRandomLen;
@@ -1350,19 +1418,18 @@
 
 /* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and
  * CKM_RC2_MAC mechanisms.  An instance of CK_RC2_PARAMS just
- * holds the effective keysize */
+ * holds the effective keysize
+ */
 typedef CK_ULONG          CK_RC2_PARAMS;
 
 typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR;
 
 
 /* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC
- * mechanism */
+ * mechanism
+ */
 typedef struct CK_RC2_CBC_PARAMS {
-  /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for
-   * v2.0 */
   CK_ULONG      ulEffectiveBits;  /* effective bits (1-1024) */
-
   CK_BYTE       iv[8];            /* IV for CBC mode */
 } CK_RC2_CBC_PARAMS;
 
@@ -1370,8 +1437,8 @@
 
 
 /* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the
- * CKM_RC2_MAC_GENERAL mechanism */
-/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */
+ * CKM_RC2_MAC_GENERAL mechanism
+ */
 typedef struct CK_RC2_MAC_GENERAL_PARAMS {
   CK_ULONG      ulEffectiveBits;  /* effective bits (1-1024) */
   CK_ULONG      ulMacLength;      /* Length of MAC in bytes */
@@ -1382,8 +1449,8 @@
 
 
 /* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and
- * CKM_RC5_MAC mechanisms */
-/* CK_RC5_PARAMS is new for v2.0 */
+ * CKM_RC5_MAC mechanisms
+ */
 typedef struct CK_RC5_PARAMS {
   CK_ULONG      ulWordsize;  /* wordsize in bits */
   CK_ULONG      ulRounds;    /* number of rounds */
@@ -1393,8 +1460,8 @@
 
 
 /* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC
- * mechanism */
-/* CK_RC5_CBC_PARAMS is new for v2.0 */
+ * mechanism
+ */
 typedef struct CK_RC5_CBC_PARAMS {
   CK_ULONG      ulWordsize;  /* wordsize in bits */
   CK_ULONG      ulRounds;    /* number of rounds */
@@ -1406,8 +1473,8 @@
 
 
 /* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the
- * CKM_RC5_MAC_GENERAL mechanism */
-/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */
+ * CKM_RC5_MAC_GENERAL mechanism
+ */
 typedef struct CK_RC5_MAC_GENERAL_PARAMS {
   CK_ULONG      ulWordsize;   /* wordsize in bits */
   CK_ULONG      ulRounds;     /* number of rounds */
@@ -1417,16 +1484,14 @@
 typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \
   CK_RC5_MAC_GENERAL_PARAMS_PTR;
 
-
 /* CK_MAC_GENERAL_PARAMS provides the parameters to most block
  * ciphers' MAC_GENERAL mechanisms.  Its value is the length of
- * the MAC */
-/* CK_MAC_GENERAL_PARAMS is new for v2.0 */
+ * the MAC
+ */
 typedef CK_ULONG          CK_MAC_GENERAL_PARAMS;
 
 typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR;
 
-/* CK_DES/AES_ECB/CBC_ENCRYPT_DATA_PARAMS are new for v2.20 */
 typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS {
   CK_BYTE      iv[8];
   CK_BYTE_PTR  pData;
@@ -1444,8 +1509,8 @@
 typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
 
 /* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the
- * CKM_SKIPJACK_PRIVATE_WRAP mechanism */
-/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */
+ * CKM_SKIPJACK_PRIVATE_WRAP mechanism
+ */
 typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS {
   CK_ULONG      ulPasswordLen;
   CK_BYTE_PTR   pPassword;
@@ -1461,12 +1526,12 @@
 } CK_SKIPJACK_PRIVATE_WRAP_PARAMS;
 
 typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \
-  CK_SKIPJACK_PRIVATE_WRAP_PTR;
+  CK_SKIPJACK_PRIVATE_WRAP_PARAMS_PTR;
 
 
 /* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the
- * CKM_SKIPJACK_RELAYX mechanism */
-/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */
+ * CKM_SKIPJACK_RELAYX mechanism
+ */
 typedef struct CK_SKIPJACK_RELAYX_PARAMS {
   CK_ULONG      ulOldWrappedXLen;
   CK_BYTE_PTR   pOldWrappedX;
@@ -1501,17 +1566,15 @@
 
 
 /* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the
- * CKM_KEY_WRAP_SET_OAEP mechanism */
-/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */
+ * CKM_KEY_WRAP_SET_OAEP mechanism
+ */
 typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS {
   CK_BYTE       bBC;     /* block contents byte */
   CK_BYTE_PTR   pX;      /* extra data */
   CK_ULONG      ulXLen;  /* length of extra data in bytes */
 } CK_KEY_WRAP_SET_OAEP_PARAMS;
 
-typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \
-  CK_KEY_WRAP_SET_OAEP_PARAMS_PTR;
-
+typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR CK_KEY_WRAP_SET_OAEP_PARAMS_PTR;
 
 typedef struct CK_SSL3_RANDOM_DATA {
   CK_BYTE_PTR  pClientRandom;
@@ -1529,7 +1592,6 @@
 typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \
   CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR;
 
-
 typedef struct CK_SSL3_KEY_MAT_OUT {
   CK_OBJECT_HANDLE hClientMacSecret;
   CK_OBJECT_HANDLE hServerMacSecret;
@@ -1553,7 +1615,6 @@
 
 typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR;
 
-/* CK_TLS_PRF_PARAMS is new for version 2.20 */
 typedef struct CK_TLS_PRF_PARAMS {
   CK_BYTE_PTR  pSeed;
   CK_ULONG     ulSeedLen;
@@ -1565,7 +1626,6 @@
 
 typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR;
 
-/* WTLS is new for version 2.20 */
 typedef struct CK_WTLS_RANDOM_DATA {
   CK_BYTE_PTR pClientRandom;
   CK_ULONG    ulClientRandomLen;
@@ -1617,7 +1677,6 @@
 
 typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR;
 
-/* CMS is new for version 2.20 */
 typedef struct CK_CMS_SIG_PARAMS {
   CK_OBJECT_HANDLE      certificateHandle;
   CK_MECHANISM_PTR      pSigningMechanism;
@@ -1643,38 +1702,45 @@
 /* The CK_EXTRACT_PARAMS is used for the
  * CKM_EXTRACT_KEY_FROM_KEY mechanism.  It specifies which bit
  * of the base key should be used as the first bit of the
- * derived key */
-/* CK_EXTRACT_PARAMS is new for v2.0 */
+ * derived key
+ */
 typedef CK_ULONG CK_EXTRACT_PARAMS;
 
 typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR;
 
-/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10.
- * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to
+/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to
  * indicate the Pseudo-Random Function (PRF) used to generate
- * key bits using PKCS #5 PBKDF2. */
+ * key bits using PKCS #5 PBKDF2.
+ */
 typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE;
 
-typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR;
-
-/* The following PRFs are defined in PKCS #5 v2.0. */
-#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001
+typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR \
+                        CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR;
 
+#define CKP_PKCS5_PBKD2_HMAC_SHA1          0x00000001UL
+#define CKP_PKCS5_PBKD2_HMAC_GOSTR3411     0x00000002UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA224        0x00000003UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA256        0x00000004UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA384        0x00000005UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA512        0x00000006UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA512_224    0x00000007UL
+#define CKP_PKCS5_PBKD2_HMAC_SHA512_256    0x00000008UL
 
-/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10.
- * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the
+/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the
  * source of the salt value when deriving a key using PKCS #5
- * PBKDF2. */
+ * PBKDF2.
+ */
 typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE;
 
-typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR;
+typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR \
+                        CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR;
 
 /* The following salt value sources are defined in PKCS #5 v2.0. */
-#define CKZ_SALT_SPECIFIED        0x00000001
+#define CKZ_SALT_SPECIFIED        0x00000001UL
 
-/* CK_PKCS5_PBKD2_PARAMS is new for v2.10.
- * CK_PKCS5_PBKD2_PARAMS is a structure that provides the
- * parameters to the CKM_PKCS5_PBKD2 mechanism. */
+/* CK_PKCS5_PBKD2_PARAMS is a structure that provides the
+ * parameters to the CKM_PKCS5_PBKD2 mechanism.
+ */
 typedef struct CK_PKCS5_PBKD2_PARAMS {
         CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE           saltSource;
         CK_VOID_PTR                                pSaltSourceData;
@@ -1689,34 +1755,248 @@
 
 typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR;
 
-/* new for v2.40 */
+/* CK_PKCS5_PBKD2_PARAMS2 is a corrected version of the CK_PKCS5_PBKD2_PARAMS
+ * structure that provides the parameters to the CKM_PKCS5_PBKD2 mechanism
+ * noting that the ulPasswordLen field is a CK_ULONG and not a CK_ULONG_PTR.
+ */
+typedef struct CK_PKCS5_PBKD2_PARAMS2 {
+        CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource;
+        CK_VOID_PTR pSaltSourceData;
+        CK_ULONG ulSaltSourceDataLen;
+        CK_ULONG iterations;
+        CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf;
+        CK_VOID_PTR pPrfData;
+        CK_ULONG ulPrfDataLen;
+        CK_UTF8CHAR_PTR pPassword;
+        CK_ULONG ulPasswordLen;
+} CK_PKCS5_PBKD2_PARAMS2;
+
+typedef CK_PKCS5_PBKD2_PARAMS2 CK_PTR CK_PKCS5_PBKD2_PARAMS2_PTR;
+
+typedef CK_ULONG CK_OTP_PARAM_TYPE;
+typedef CK_OTP_PARAM_TYPE CK_PARAM_TYPE; /* backward compatibility */
+
+typedef struct CK_OTP_PARAM {
+    CK_OTP_PARAM_TYPE type;
+    CK_VOID_PTR pValue;
+    CK_ULONG ulValueLen;
+} CK_OTP_PARAM;
+
+typedef CK_OTP_PARAM CK_PTR CK_OTP_PARAM_PTR;
+
+typedef struct CK_OTP_PARAMS {
+    CK_OTP_PARAM_PTR pParams;
+    CK_ULONG ulCount;
+} CK_OTP_PARAMS;
+
+typedef CK_OTP_PARAMS CK_PTR CK_OTP_PARAMS_PTR;
+
+typedef struct CK_OTP_SIGNATURE_INFO {
+    CK_OTP_PARAM_PTR pParams;
+    CK_ULONG ulCount;
+} CK_OTP_SIGNATURE_INFO;
+
+typedef CK_OTP_SIGNATURE_INFO CK_PTR CK_OTP_SIGNATURE_INFO_PTR;
+
+#define CK_OTP_VALUE          0UL
+#define CK_OTP_PIN            1UL
+#define CK_OTP_CHALLENGE      2UL
+#define CK_OTP_TIME           3UL
+#define CK_OTP_COUNTER        4UL
+#define CK_OTP_FLAGS          5UL
+#define CK_OTP_OUTPUT_LENGTH  6UL
+#define CK_OTP_OUTPUT_FORMAT  7UL
+
+#define CKF_NEXT_OTP          0x00000001UL
+#define CKF_EXCLUDE_TIME      0x00000002UL
+#define CKF_EXCLUDE_COUNTER   0x00000004UL
+#define CKF_EXCLUDE_CHALLENGE 0x00000008UL
+#define CKF_EXCLUDE_PIN       0x00000010UL
+#define CKF_USER_FRIENDLY_OTP 0x00000020UL
+
+typedef struct CK_KIP_PARAMS {
+    CK_MECHANISM_PTR  pMechanism;
+    CK_OBJECT_HANDLE  hKey;
+    CK_BYTE_PTR       pSeed;
+    CK_ULONG          ulSeedLen;
+} CK_KIP_PARAMS;
+
+typedef CK_KIP_PARAMS CK_PTR CK_KIP_PARAMS_PTR;
+
+typedef struct CK_AES_CTR_PARAMS {
+    CK_ULONG ulCounterBits;
+    CK_BYTE cb[16];
+} CK_AES_CTR_PARAMS;
+
+typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;
+
+typedef struct CK_GCM_PARAMS {
+    CK_BYTE_PTR       pIv;
+    CK_ULONG          ulIvLen;
+    CK_BYTE_PTR       pAAD;
+    CK_ULONG          ulAADLen;
+    CK_ULONG          ulTagBits;
+} CK_GCM_PARAMS;
+
+typedef CK_GCM_PARAMS CK_PTR CK_GCM_PARAMS_PTR;
+
+typedef struct CK_CCM_PARAMS {
+    CK_ULONG          ulDataLen;
+    CK_BYTE_PTR       pNonce;
+    CK_ULONG          ulNonceLen;
+    CK_BYTE_PTR       pAAD;
+    CK_ULONG          ulAADLen;
+    CK_ULONG          ulMACLen;
+} CK_CCM_PARAMS;
+
+typedef CK_CCM_PARAMS CK_PTR CK_CCM_PARAMS_PTR;
+
+/* Deprecated. Use CK_GCM_PARAMS */
+typedef struct CK_AES_GCM_PARAMS {
+  CK_BYTE_PTR pIv;
+  CK_ULONG ulIvLen;
+  CK_ULONG ulIvBits;
+  CK_BYTE_PTR pAAD;
+  CK_ULONG ulAADLen;
+  CK_ULONG ulTagBits;
+} CK_AES_GCM_PARAMS;
+
+typedef CK_AES_GCM_PARAMS CK_PTR CK_AES_GCM_PARAMS_PTR;
+
+/* Deprecated. Use CK_CCM_PARAMS */
+typedef struct CK_AES_CCM_PARAMS {
+    CK_ULONG          ulDataLen;
+    CK_BYTE_PTR       pNonce;
+    CK_ULONG          ulNonceLen;
+    CK_BYTE_PTR       pAAD;
+    CK_ULONG          ulAADLen;
+    CK_ULONG          ulMACLen;
+} CK_AES_CCM_PARAMS;
+
+typedef CK_AES_CCM_PARAMS CK_PTR CK_AES_CCM_PARAMS_PTR;
+
+typedef struct CK_CAMELLIA_CTR_PARAMS {
+    CK_ULONG          ulCounterBits;
+    CK_BYTE           cb[16];
+} CK_CAMELLIA_CTR_PARAMS;
+
+typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR;
+
+typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS {
+    CK_BYTE           iv[16];
+    CK_BYTE_PTR       pData;
+    CK_ULONG          length;
+} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
+                                CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS {
+    CK_BYTE           iv[16];
+    CK_BYTE_PTR       pData;
+    CK_ULONG          length;
+} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
+                                CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+typedef struct CK_DSA_PARAMETER_GEN_PARAM {
+    CK_MECHANISM_TYPE  hash;
+    CK_BYTE_PTR        pSeed;
+    CK_ULONG           ulSeedLen;
+    CK_ULONG           ulIndex;
+} CK_DSA_PARAMETER_GEN_PARAM;
+
+typedef CK_DSA_PARAMETER_GEN_PARAM CK_PTR CK_DSA_PARAMETER_GEN_PARAM_PTR;
+
+typedef struct CK_ECDH_AES_KEY_WRAP_PARAMS {
+    CK_ULONG           ulAESKeyBits;
+    CK_EC_KDF_TYPE     kdf;
+    CK_ULONG           ulSharedDataLen;
+    CK_BYTE_PTR        pSharedData;
+} CK_ECDH_AES_KEY_WRAP_PARAMS;
+
+typedef CK_ECDH_AES_KEY_WRAP_PARAMS CK_PTR CK_ECDH_AES_KEY_WRAP_PARAMS_PTR;
+
+typedef CK_ULONG CK_JAVA_MIDP_SECURITY_DOMAIN;
+
+typedef CK_ULONG CK_CERTIFICATE_CATEGORY;
+
+typedef struct CK_RSA_AES_KEY_WRAP_PARAMS {
+    CK_ULONG                      ulAESKeyBits;
+    CK_RSA_PKCS_OAEP_PARAMS_PTR   pOAEPParams;
+} CK_RSA_AES_KEY_WRAP_PARAMS;
+
+typedef CK_RSA_AES_KEY_WRAP_PARAMS CK_PTR CK_RSA_AES_KEY_WRAP_PARAMS_PTR;
 
 typedef struct CK_TLS12_MASTER_KEY_DERIVE_PARAMS {
-  CK_SSL3_RANDOM_DATA       RandomInfo;
-  CK_VERSION_PTR            pVersion;
-  CK_MECHANISM_TYPE         prfHashMechanism;
+    CK_SSL3_RANDOM_DATA       RandomInfo;
+    CK_VERSION_PTR            pVersion;
+    CK_MECHANISM_TYPE         prfHashMechanism;
 } CK_TLS12_MASTER_KEY_DERIVE_PARAMS;
 
-typedef CK_TLS12_MASTER_KEY_DERIVE_PARAMS CK_PTR CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR;
+typedef CK_TLS12_MASTER_KEY_DERIVE_PARAMS CK_PTR \
+                                CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR;
 
 typedef struct CK_TLS12_KEY_MAT_PARAMS {
-  CK_ULONG ulMacSizeInBits;
-  CK_ULONG ulKeySizeInBits;
-  CK_ULONG ulIVSizeInBits;
-  CK_BBOOL bIsExport;
-  CK_SSL3_RANDOM_DATA RandomInfo;
-  CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
-  CK_MECHANISM_TYPE prfHashMechanism;
+    CK_ULONG                  ulMacSizeInBits;
+    CK_ULONG                  ulKeySizeInBits;
+    CK_ULONG                  ulIVSizeInBits;
+    CK_BBOOL                  bIsExport;
+    CK_SSL3_RANDOM_DATA       RandomInfo;
+    CK_SSL3_KEY_MAT_OUT_PTR   pReturnedKeyMaterial;
+    CK_MECHANISM_TYPE         prfHashMechanism;
 } CK_TLS12_KEY_MAT_PARAMS;
 
 typedef CK_TLS12_KEY_MAT_PARAMS CK_PTR CK_TLS12_KEY_MAT_PARAMS_PTR;
 
+typedef struct CK_TLS_KDF_PARAMS {
+    CK_MECHANISM_TYPE         prfMechanism;
+    CK_BYTE_PTR               pLabel;
+    CK_ULONG                  ulLabelLength;
+    CK_SSL3_RANDOM_DATA       RandomInfo;
+    CK_BYTE_PTR               pContextData;
+    CK_ULONG                  ulContextDataLength;
+} CK_TLS_KDF_PARAMS;
+
+typedef CK_TLS_KDF_PARAMS CK_PTR CK_TLS_KDF_PARAMS_PTR;
+
 typedef struct CK_TLS_MAC_PARAMS {
-  CK_MECHANISM_TYPE prfMechanism;
-  CK_ULONG ulMacLength;
-  CK_ULONG ulServerOrClient;
+    CK_MECHANISM_TYPE         prfMechanism;
+    CK_ULONG                  ulMacLength;
+    CK_ULONG                  ulServerOrClient;
 } CK_TLS_MAC_PARAMS;
 
 typedef CK_TLS_MAC_PARAMS CK_PTR CK_TLS_MAC_PARAMS_PTR;
 
-#endif
+typedef struct CK_GOSTR3410_DERIVE_PARAMS {
+    CK_EC_KDF_TYPE            kdf;
+    CK_BYTE_PTR               pPublicData;
+    CK_ULONG                  ulPublicDataLen;
+    CK_BYTE_PTR               pUKM;
+    CK_ULONG                  ulUKMLen;
+} CK_GOSTR3410_DERIVE_PARAMS;
+
+typedef CK_GOSTR3410_DERIVE_PARAMS CK_PTR CK_GOSTR3410_DERIVE_PARAMS_PTR;
+
+typedef struct CK_GOSTR3410_KEY_WRAP_PARAMS {
+    CK_BYTE_PTR               pWrapOID;
+    CK_ULONG                  ulWrapOIDLen;
+    CK_BYTE_PTR               pUKM;
+    CK_ULONG                  ulUKMLen;
+    CK_OBJECT_HANDLE          hKey;
+} CK_GOSTR3410_KEY_WRAP_PARAMS;
+
+typedef CK_GOSTR3410_KEY_WRAP_PARAMS CK_PTR CK_GOSTR3410_KEY_WRAP_PARAMS_PTR;
+
+typedef struct CK_SEED_CBC_ENCRYPT_DATA_PARAMS {
+    CK_BYTE                   iv[16];
+    CK_BYTE_PTR               pData;
+    CK_ULONG                  length;
+} CK_SEED_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_SEED_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
+                                        CK_SEED_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+#endif /* _PKCS11T_H_ */
+
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11wrapper.h	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11wrapper.h	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -69,11 +69,12 @@
 
 #define CKA_NETSCAPE_BASE                       (0x80000000 + 0x4E534350)
 #define CKA_NETSCAPE_TRUST_BASE                 (CKA_NETSCAPE_BASE + 0x2000)
-
 #define CKA_NETSCAPE_TRUST_SERVER_AUTH          (CKA_NETSCAPE_TRUST_BASE + 8)
 #define CKA_NETSCAPE_TRUST_CLIENT_AUTH          (CKA_NETSCAPE_TRUST_BASE + 9)
 #define CKA_NETSCAPE_TRUST_CODE_SIGNING (CKA_NETSCAPE_TRUST_BASE + 10)
 #define CKA_NETSCAPE_TRUST_EMAIL_PROTECTION     (CKA_NETSCAPE_TRUST_BASE + 11)
+#define CKA_NETSCAPE_DB                         0xD5A0DB00
+#define CKM_NSS_TLS_PRF_GENERAL                 0x80000373
 
 /*
 
@@ -154,11 +155,11 @@
 #define P11_ENABLE_GETNATIVEKEYINFO
 #define P11_ENABLE_CREATENATIVEKEY
 
+
 /* include the platform dependent part of the header */
 #include "p11_md.h"
 
 #include "pkcs11.h"
-#include "pkcs-11v2-20a3.h"
 #include <jni.h>
 #include <jni_util.h>
 #include <stdarg.h>
@@ -206,8 +207,6 @@
 #define ckULongToJSize(x)       ((jsize) x)
 #define unsignedIntToCKULong(x) ((CK_ULONG) x)
 
-//#define P11_DEBUG
-
 #ifdef P11_DEBUG
 #define TRACE0(s) { printf(s); fflush(stdout); }
 #define TRACE1(s, p1) { printf(s, p1); fflush(stdout); }
@@ -228,6 +227,8 @@
 
 #define CK_ASSERT_OK 0L
 
+#define CLASS_P11PSSSIGNATURE "sun/security/pkcs11/P11PSSSignature"
+
 #define CLASS_INFO "sun/security/pkcs11/wrapper/CK_INFO"
 #define CLASS_VERSION "sun/security/pkcs11/wrapper/CK_VERSION"
 #define CLASS_SLOT_INFO "sun/security/pkcs11/wrapper/CK_SLOT_INFO"
@@ -249,15 +250,18 @@
 
 
 /* mechanism parameter classes */
+#define CLASS_AES_CTR_PARAMS "sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS"
+#define CLASS_GCM_PARAMS "sun/security/pkcs11/wrapper/CK_GCM_PARAMS"
+#define CLASS_CCM_PARAMS "sun/security/pkcs11/wrapper/CK_CCM_PARAMS"
+#define CLASS_RSA_PKCS_PSS_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS"
+#define CLASS_RSA_PKCS_OAEP_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS"
 
-#define CLASS_RSA_PKCS_OAEP_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS"
 #define CLASS_MAC_GENERAL_PARAMS "sun/security/pkcs11/wrapper/CK_MAC_GENERAL_PARAMS"
 #define CLASS_PBE_PARAMS "sun/security/pkcs11/wrapper/CK_PBE_PARAMS"
 #define PBE_INIT_VECTOR_SIZE 8
 #define CLASS_PKCS5_PBKD2_PARAMS "sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS"
 #define CLASS_EXTRACT_PARAMS "sun/security/pkcs11/wrapper/CK_EXTRACT_PARAMS"
 
-#define CLASS_RSA_PKCS_PSS_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS"
 #define CLASS_ECDH1_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS"
 #define CLASS_ECDH2_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS"
 #define CLASS_X9_42_DH1_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS"
@@ -287,7 +291,7 @@
 #define CLASS_TLS12_KEY_MAT_PARAMS "sun/security/pkcs11/wrapper/CK_TLS12_KEY_MAT_PARAMS"
 #define CLASS_TLS_PRF_PARAMS "sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS"
 #define CLASS_TLS_MAC_PARAMS "sun/security/pkcs11/wrapper/CK_TLS_MAC_PARAMS"
-#define CLASS_AES_CTR_PARAMS "sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS"
+
 
 /* function to convert a PKCS#11 return value other than CK_OK into a Java Exception
  * or to throw a PKCS11RuntimeException
@@ -300,11 +304,12 @@
 void throwPKCS11RuntimeException(JNIEnv *env, const char *message);
 void throwDisconnectedRuntimeException(JNIEnv *env);
 
-/* function to free CK_ATTRIBUTE array
+/* functions to free CK structures and pointers
  */
 void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len);
+void freeCKMechanismPtr(CK_MECHANISM_PTR mechPtr);
 
-/* funktions to convert Java arrays to a CK-type array and the array length */
+/* functions to convert Java arrays to a CK-type array and the array length */
 
 void jBooleanArrayToCKBBoolArray(JNIEnv *env, const jbooleanArray jArray, CK_BBOOL **ckpArray, CK_ULONG_PTR ckLength);
 void jByteArrayToCKByteArray(JNIEnv *env, const jbyteArray jArray, CK_BYTE_PTR *ckpArray, CK_ULONG_PTR ckLength);
@@ -316,7 +321,7 @@
 /*void jObjectArrayToCKVoidPtrArray(JNIEnv *env, const jobjectArray jArray, CK_VOID_PTR_PTR ckpArray, CK_ULONG_PTR ckpLength); */
 
 
-/* funktions to convert a CK-type array and the array length to a Java array */
+/* functions to convert a CK-type array and the array length to a Java array */
 
 jbyteArray ckByteArrayToJByteArray(JNIEnv *env, const CK_BYTE_PTR ckpArray, CK_ULONG ckLength);
 jlongArray ckULongArrayToJLongArray(JNIEnv *env, const CK_ULONG_PTR ckpArray, CK_ULONG ckLength);
@@ -324,7 +329,7 @@
 jcharArray ckUTF8CharArrayToJCharArray(JNIEnv *env, const CK_UTF8CHAR_PTR ckpArray, CK_ULONG ckLength);
 
 
-/* funktions to convert a CK-type structure or a pointer to a CK-value to a Java object */
+/* functions to convert a CK-type structure or a pointer to a CK-value to a Java object */
 
 jobject ckBBoolPtrToJBooleanObject(JNIEnv *env, const CK_BBOOL* ckpValue);
 jobject ckULongPtrToJLongObject(JNIEnv *env, const CK_ULONG_PTR ckpValue);
@@ -334,12 +339,12 @@
 jobject ckAttributePtrToJAttribute(JNIEnv *env, const CK_ATTRIBUTE_PTR ckpAttribute);
 
 
-/* funktion to convert the CK-value used by the CK_ATTRIBUTE structure to a Java object */
+/* function to convert the CK-value used by the CK_ATTRIBUTE structure to a Java object */
 
 jobject ckAttributeValueToJObject(JNIEnv *env, const CK_ATTRIBUTE_PTR ckpAttribute);
 
 
-/* funktions to convert a Java object to a CK-type structure or a pointer to a CK-value */
+/* functions to convert a Java object to a CK-type structure or a pointer to a CK-value */
 
 CK_BBOOL* jBooleanObjectToCKBBoolPtr(JNIEnv *env, jobject jObject);
 CK_BYTE_PTR jByteObjectToCKBytePtr(JNIEnv *env, jobject jObject);
@@ -349,44 +354,35 @@
 CK_VERSION_PTR jVersionToCKVersionPtr(JNIEnv *env, jobject jVersion);
 CK_DATE * jDateObjectPtrToCKDatePtr(JNIEnv *env, jobject jDate);
 CK_ATTRIBUTE jAttributeToCKAttribute(JNIEnv *env, jobject jAttribute);
-/*CK_MECHANISM jMechanismToCKMechanism(JNIEnv *env, jobject jMechanism);*/
-void jMechanismToCKMechanism(JNIEnv *env, jobject jMechanism, CK_MECHANISM_PTR ckMechanismPtr);
+CK_MECHANISM_PTR jMechanismToCKMechanismPtr(JNIEnv *env, jobject jMechanism);
 
 
-/* funktions to convert Java objects used by the Mechanism and Attribute class to a CK-type structure */
-
-void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *pLength);
-void jMechanismParameterToCKMechanismParameter(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength);
+/* functions to convert Java objects used by the Mechanism and Attribute class to a CK-type structure */
+CK_VOID_PTR jObjectToPrimitiveCKObjectPtr(JNIEnv *env, jobject jObject, CK_ULONG *ckpLength);
+CK_VOID_PTR jMechParamToCKMechParamPtr(JNIEnv *env, jobject jParam, CK_MECHANISM_TYPE, CK_ULONG
+*ckpLength);
 
 
 /* functions to convert a specific Java mechanism parameter object to a CK-mechanism parameter structure */
 
-CK_RSA_PKCS_OAEP_PARAMS jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam);
-CK_KEA_DERIVE_PARAMS jKeaDeriveParamToCKKeaDeriveParam(JNIEnv *env, jobject jParam);
-CK_RC2_CBC_PARAMS jRc2CbcParamToCKRc2CbcParam(JNIEnv *env, jobject jParam);
-CK_RC2_MAC_GENERAL_PARAMS jRc2MacGeneralParamToCKRc2MacGeneralParam(JNIEnv *env, jobject jParam);
-CK_RC5_PARAMS jRc5ParamToCKRc5Param(JNIEnv *env, jobject jParam);
-CK_RC5_CBC_PARAMS jRc5CbcParamToCKRc5CbcParam(JNIEnv *env, jobject jParam);
-CK_RC5_MAC_GENERAL_PARAMS jRc5MacGeneralParamToCKRc5MacGeneralParam(JNIEnv *env, jobject jParam);
-CK_SKIPJACK_PRIVATE_WRAP_PARAMS jSkipjackPrivateWrapParamToCKSkipjackPrivateWrapParam(JNIEnv *env, jobject jParam);
-CK_SKIPJACK_RELAYX_PARAMS jSkipjackRelayxParamToCKSkipjackRelayxParam(JNIEnv *env, jobject jParam);
-CK_PBE_PARAMS jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam);
+void jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam, CK_RSA_PKCS_OAEP_PARAMS_PTR ckParamPtr);
+void jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam, CK_PBE_PARAMS_PTR ckParamPtr);
 void copyBackPBEInitializationVector(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
-CK_PKCS5_PBKD2_PARAMS jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam);
-CK_KEY_WRAP_SET_OAEP_PARAMS jKeyWrapSetOaepParamToCKKeyWrapSetOaepParam(JNIEnv *env, jobject jParam);
+void jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam, CK_PKCS5_PBKD2_PARAMS_PTR ckParamPtr);
 void copyBackSetUnwrappedKey(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
-CK_SSL3_MASTER_KEY_DERIVE_PARAMS jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env, jobject jParam);
+void jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env, jobject jParam, CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckParamPtr);
 void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
 void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
-CK_SSL3_KEY_MAT_PARAMS jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam);
+void jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam, CK_SSL3_KEY_MAT_PARAMS_PTR ckParamPtr);
 void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
 void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
 CK_KEY_DERIVATION_STRING_DATA jKeyDerivationStringDataToCKKeyDerivationStringData(JNIEnv *env, jobject jParam);
-CK_RSA_PKCS_PSS_PARAMS jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam);
-CK_ECDH1_DERIVE_PARAMS jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam);
-CK_ECDH2_DERIVE_PARAMS jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam);
-CK_X9_42_DH1_DERIVE_PARAMS jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam);
-CK_X9_42_DH2_DERIVE_PARAMS jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam);
+void jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam, CK_RSA_PKCS_PSS_PARAMS_PTR ckParamPtr);
+void jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam, CK_ECDH1_DERIVE_PARAMS_PTR ckParamPtr);
+void jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam,
+CK_ECDH2_DERIVE_PARAMS_PTR ckParamPtr);
+void jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam, CK_X9_42_DH1_DERIVE_PARAMS_PTR ckParamPtr);
+void jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam, CK_X9_42_DH2_DERIVE_PARAMS_PTR ckParamPtr);
 
 
 /* functions to convert the InitArgs object for calling the right Java mutex functions */
@@ -450,6 +446,7 @@
 extern jfieldID pNativeDataID;
 extern jfieldID mech_mechanismID;
 extern jfieldID mech_pParameterID;
+extern jfieldID mech_pHandleID;
 
 extern jclass jByteArrayClass;
 extern jclass jLongClass;
--- a/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotMetaData.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotMetaData.java	Wed Jun 12 10:02:49 2019 +0530
@@ -31,6 +31,7 @@
     private byte[] scopesDescBytes;
     private byte[] relocBytes;
     private byte[] exceptionBytes;
+    private byte[] implicitExceptionBytes;
     private byte[] oopMaps;
     private Object[] metadata;
 
@@ -62,6 +63,10 @@
         return exceptionBytes;
     }
 
+    public byte[] implicitExceptionBytes() {
+        return implicitExceptionBytes;
+    }
+
     public byte[] oopMaps() {
         return oopMaps;
     }
--- a/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl.java	Wed Jun 12 10:02:49 2019 +0530
@@ -241,7 +241,7 @@
 
     @Override
     public boolean canBeStaticallyBound() {
-        return (isFinal() || isPrivate() || isStatic() || holder.isLeaf()) && isConcrete();
+        return (isFinal() || isPrivate() || isStatic() || holder.isLeaf() || isConstructor()) && isConcrete();
     }
 
     @Override
@@ -406,6 +406,8 @@
 
     @Override
     public ResolvedJavaMethod uniqueConcreteMethod(HotSpotResolvedObjectType receiver) {
+        assert !canBeStaticallyBound() : this;
+
         if (receiver.isInterface()) {
             // Cannot trust interfaces. Because of:
             // interface I { void foo(); }
@@ -417,6 +419,7 @@
             // seeing A.foo().
             return null;
         }
+        assert !receiver.isLinked() || isInVirtualMethodTable(receiver);
         if (this.isDefault()) {
             // CHA for default methods doesn't work and may crash the VM
             return null;
--- a/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCI.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.runtime/src/jdk/vm/ci/runtime/JVMCI.java	Wed Jun 12 10:02:49 2019 +0530
@@ -71,6 +71,8 @@
                         errorMessage.format("Currently used Java home directory is %s.%n", javaHome);
                         errorMessage.format("Currently used VM configuration is: %s", vmName);
                         throw new UnsupportedOperationException(errorMessage.toString());
+                    } finally {
+                        initializing = false;
                     }
                 }
             }
--- a/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1300,7 +1300,7 @@
 
         String alias = storeHash.get(c);
         if (alias != null) {
-            certStr.append(space).append(alias);
+            certStr.append(space).append("(").append(alias).append(")");
         }
 
         if (x509Cert != null) {
@@ -1425,37 +1425,43 @@
         }
 
         int result = 0;
-        List<? extends Certificate> certs = signer.getSignerCertPath().getCertificates();
-        for (Certificate c : certs) {
-            String alias = storeHash.get(c);
-            if (alias != null) {
-                if (alias.startsWith("(")) {
-                    result |= IN_KEYSTORE;
-                }
-                if (ckaliases.contains(alias.substring(1, alias.length() - 1))) {
-                    result |= SIGNED_BY_ALIAS;
-                }
-            } else {
-                if (store != null) {
-                    try {
+        if (store != null) {
+            try {
+                List<? extends Certificate> certs =
+                        signer.getSignerCertPath().getCertificates();
+                for (Certificate c : certs) {
+                    String alias = storeHash.get(c);
+                    if (alias == null) {
                         alias = store.getCertificateAlias(c);
-                    } catch (KeyStoreException kse) {
-                        // never happens, because keystore has been loaded
+                        if (alias != null) {
+                            storeHash.put(c, alias);
+                        }
                     }
                     if (alias != null) {
-                        storeHash.put(c, "(" + alias + ")");
                         result |= IN_KEYSTORE;
                     }
+                    for (String ckalias : ckaliases) {
+                        if (c.equals(store.getCertificate(ckalias))) {
+                            result |= SIGNED_BY_ALIAS;
+                            // must continue with next certificate c and cannot
+                            // return or break outer loop because has to fill
+                            // storeHash for printCert
+                            break;
+                        }
+                    }
                 }
-                if (ckaliases.contains(alias)) {
-                    result |= SIGNED_BY_ALIAS;
-                }
+            } catch (KeyStoreException kse) {
+                // never happens, because keystore has been loaded
             }
         }
         cacheForInKS.put(signer, result);
         return result;
     }
 
+    /**
+     * Maps certificates (as keys) to alias names associated in the keystore
+     * {@link #store} (as values).
+     */
     Hashtable<Certificate, String> storeHash = new Hashtable<>();
 
     int inKeyStore(CodeSigner[] signers) {
--- a/src/jdk.jdeps/share/classes/com/sun/tools/javap/JavapTask.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.jdeps/share/classes/com/sun/tools/javap/JavapTask.java	Wed Jun 12 10:02:49 2019 +0530
@@ -944,7 +944,8 @@
         String[] fmOptions = {
             "--module-path", "--system",
             "--class-path", "-classpath", "-cp",
-            "-bootclasspath"
+            "-bootclasspath",
+            "--multi-release"
         };
 
         for (String o: fmOptions) {
--- a/src/jdk.jdeps/share/classes/com/sun/tools/javap/resources/javap.properties	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.jdeps/share/classes/com/sun/tools/javap/resources/javap.properties	Wed Jun 12 10:02:49 2019 +0530
@@ -92,6 +92,9 @@
 main.opt.module_path=\
 \  --module-path <path>             Specify where to find application modules
 
+main.opt.multi_release=\
+\  --multi-release <version>        Specify the version to use in multi-release JAR files
+
 main.opt.constants=\
 \  -constants                       Show final constants
 
--- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java	Wed Jun 12 10:02:49 2019 +0530
@@ -24,6 +24,7 @@
  */
 package jdk.jfr.internal.dcmd;
 
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.InvalidPathException;
@@ -105,13 +106,17 @@
         if (duration == null && Boolean.FALSE.equals(dumpOnExit) && path != null) {
             throw new DCmdException("Filename can only be set for a time bound recording or if dumponexit=true. Set duration/dumponexit or omit filename.");
         }
-
+        if (settings.length == 1 && settings[0].length() == 0) {
+            throw new DCmdException("No settings specified. Use settings=none to start without any settings");
+        }
         Map<String, String> s = new HashMap<>();
         for (String configName : settings) {
             try {
                 s.putAll(JFC.createKnown(configName).getSettings());
+            } catch(FileNotFoundException e) {
+                throw new DCmdException("Could not find settings file'" + configName + "'", e);
             } catch (IOException | ParseException e) {
-                throw new DCmdException("Could not parse setting " + settings[0], e);
+                throw new DCmdException("Could not parse settings file '" + settings[0] + "'", e);
             }
         }
 
--- a/src/jdk.jfr/share/classes/jdk/jfr/internal/jfc/JFC.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/jfc/JFC.java	Wed Jun 12 10:02:49 2019 +0530
@@ -127,7 +127,11 @@
 
     public static String nameFromPath(Path file) throws IOException {
         String f = nullSafeFileName(file);
-        return f.substring(0, f.length() - JFCParser.FILE_EXTENSION.length());
+        if (f.endsWith(JFCParser.FILE_EXTENSION)) {
+            return f.substring(0, f.length() - JFCParser.FILE_EXTENSION.length());
+        } else  {
+            return f;
+        }
     }
 
     // Invoked by DCmdStart
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
 import com.sun.javatest.Harness;
 import com.sun.javatest.Parameters;
 import com.sun.javatest.TestResult;
-import com.sun.javatest.InterviewParameters;
+import com.sun.javatest.regtest.config.RegressionParameters;
 import jdk.test.failurehandler.*;
 
 import java.io.File;
@@ -46,8 +46,8 @@
     public static final String LOG_FILENAME = "environment.log";
     public static final String ENVIRONMENT_OUTPUT = "environment.html";
 
-    private String compileJdk;
-    private String testJdk;
+    private Path compileJdk;
+    private Path testJdk;
 
     /*
      * The harness calls this method after each test.
@@ -80,7 +80,7 @@
             log.printf("%s ---%n", name);
             GathererFactory gathererFactory = new GathererFactory(
                     OS.current().family, workDir, log,
-                    Paths.get(testJdk), Paths.get(compileJdk));
+                    testJdk, compileJdk);
             gatherEnvInfo(workDir, name, log,
                     gathererFactory.getEnvironmentInfoGatherer());
         } catch (Throwable e) {
@@ -117,12 +117,9 @@
      */
     @Override
     public void startingTestRun(Parameters params) {
-        // TODO find a better way to get JDKs
-        InterviewParameters rp = (InterviewParameters) params;
-        Map<String, String> map = new HashMap<>();
-        rp.save(map);
-        compileJdk = map.get("regtest.compilejdk");
-        testJdk = map.get("regtest.testjdk");
+        RegressionParameters rp = (RegressionParameters) params;
+        compileJdk = rp.getCompileJDK().getAbsoluteFile().toPath();
+        testJdk = rp.getTestJDK().getAbsoluteFile().toPath();
     }
 
     @Override
--- a/test/hotspot/jtreg/ProblemList.txt	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/ProblemList.txt	Wed Jun 12 10:02:49 2019 +0530
@@ -43,12 +43,14 @@
 compiler/ciReplay/TestSAServer.java 8029528 generic-all
 compiler/codecache/stress/OverloadCompileQueueTest.java 8166554 generic-all
 compiler/codegen/Test6896617.java 8193479 generic-all
+compiler/compilercontrol/jcmd/ClearDirectivesFileStackTest.java 8225370 generic-all
 compiler/jvmci/compilerToVM/GetFlagValueTest.java 8204459 generic-all
 compiler/jvmci/compilerToVM/GetResolvedJavaTypeTest.java 8158860 generic-all
 compiler/jvmci/compilerToVM/InvalidateInstalledCodeTest.java 8163894 generic-all
 compiler/tiered/LevelTransitionTest.java 8067651 generic-all
-compiler/types/correctness/CorrectnessTest.java 8066173 generic-all
-compiler/types/correctness/OffTest.java 8066173 generic-all
+
+compiler/types/correctness/CorrectnessTest.java 8066173 solaris-sparcv9
+compiler/types/correctness/OffTest.java         8066173 solaris-sparcv9
 
 compiler/c2/Test6852078.java 8194310 generic-all
 compiler/c2/Test8004741.java 8214904 generic-all
@@ -76,7 +78,6 @@
 gc/stress/gclocker/TestGCLockerWithG1.java 8180622 generic-all
 gc/stress/TestJNIBlockFullGC/TestJNIBlockFullGC.java 8192647 generic-all
 gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java 8193639 solaris-all
-gc/stress/TestReclaimStringsLeaksMemory.java 8224847 generic-all
 
 #############################################################################
 
--- a/test/hotspot/jtreg/compiler/c2/Test8202414.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/c2/Test8202414.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2019, Huawei Technologies Co. Ltd. All rights reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/GCTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-/*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8072008
- * @requires vm.opt.final.ClassUnloading
- * @library /test/lib ../patches
- * @modules java.base/jdk.internal.misc
- *          java.base/jdk.internal.vm.annotation
- *
- * @build java.base/java.lang.invoke.MethodHandleHelper
- * @build sun.hotspot.WhiteBox
- * @run main/bootclasspath/othervm -XX:+IgnoreUnrecognizedVMOptions
- *                                 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
- *                                 -Xbatch -XX:-TieredCompilation -XX:CICompilerCount=1
- *                                 -XX:+FoldStableValues
- *                                 compiler.jsr292.NonInlinedCall.GCTest
- */
-
-package compiler.jsr292.NonInlinedCall;
-
-import jdk.internal.vm.annotation.DontInline;
-import jdk.internal.vm.annotation.Stable;
-import sun.hotspot.WhiteBox;
-
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandleHelper;
-import java.lang.invoke.MethodHandleHelper.NonInlinedReinvoker;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodType;
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-
-import static jdk.test.lib.Asserts.assertEquals;
-
-public class GCTest {
-    static final MethodHandles.Lookup LOOKUP = MethodHandleHelper.IMPL_LOOKUP;
-
-    static class T {
-        static int f1() { return 0; }
-        static int f2() { return 1; }
-    }
-
-    static @Stable MethodHandle mh;
-    static PhantomReference<Object> lform;
-
-    static final ReferenceQueue<Object> rq = new ReferenceQueue<>();
-    static final WhiteBox WB = WhiteBox.getWhiteBox();
-
-    @DontInline
-    static int invokeBasic() {
-        try {
-            return MethodHandleHelper.invokeBasicI(mh);
-        } catch (Throwable e) {
-            throw new Error(e);
-        }
-    }
-
-    static void test(int expected) {
-        for (int i = 0; i < 20_000; i++) {
-            invokeBasic();
-        }
-        assertEquals(invokeBasic(), expected);
-    }
-
-    public static void main(String[] args) throws Exception {
-        mh = NonInlinedReinvoker.make(
-                LOOKUP.findStatic(T.class, "f1", MethodType.methodType(int.class)));
-
-        // Monitor LambdaForm GC
-        lform = new PhantomReference<>(MethodHandleHelper.getLambdaForm(mh), rq);
-
-        test(0);
-        WB.clearInlineCaches();
-        test(0);
-
-        mh = NonInlinedReinvoker.make(
-                LOOKUP.findStatic(T.class, "f2", MethodType.methodType(int.class)));
-
-        Reference<?> ref = null;
-        while (ref == null) {
-            WB.fullGC();
-            try {
-                ref = rq.remove(1000);
-            } catch (InterruptedException e) { /*ignore*/ }
-        }
-
-        test(1);
-        WB.clearInlineCaches();
-        test(1);
-
-        System.out.println("TEST PASSED");
-    }
-}
--- a/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/InvokeTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/InvokeTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,6 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandleHelper;
-import java.lang.invoke.MethodHandleHelper.NonInlinedReinvoker;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
 
@@ -58,7 +57,6 @@
     static final MethodHandle defaultMH; // invokevirtual   T.f3
     static final MethodHandle specialMH; // invokespecial   T.f4 T
     static final MethodHandle privateMH; // invokespecial   I.f4 T
-    static final MethodHandle basicMH;
 
     static final MethodHandle intrinsicMH; // invokevirtual Object.hashCode
 
@@ -76,7 +74,6 @@
             defaultMH  = LOOKUP.findVirtual(T.class, "f3", mtype);
             specialMH  = LOOKUP.findSpecial(T.class, "f4", mtype, T.class);
             privateMH  = LOOKUP.findSpecial(I.class, "f4", mtype, I.class);
-            basicMH    = NonInlinedReinvoker.make(staticMH);
             intrinsicMH = LOOKUP.findVirtual(Object.class, "hashCode", MethodType.methodType(int.class));
         } catch (Exception e) {
             throw new Error(e);
@@ -194,16 +191,6 @@
         }
     }
 
-    @DontInline
-    static void invokeBasic() {
-        try {
-            Class<?> cls = (Class<?>)MethodHandleHelper.invokeBasicL(basicMH);
-            assertEquals(cls, T.class);
-        } catch (Throwable e) {
-            throw new Error(e);
-        }
-    }
-
     static void run(Runnable r) {
         for (int i = 0; i < 20_000; i++) {
             r.run();
@@ -290,17 +277,10 @@
         run(() -> linkToStatic());
     }
 
-    static void testBasic() {
-        System.out.println("invokeBasic");
-        // static call
-        run(() -> invokeBasic());
-    }
-
     public static void main(String[] args) {
         testVirtual();
         testInterface();
         testSpecial();
         testStatic();
-        testBasic();
     }
 }
--- a/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/RedefineTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/RedefineTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -114,7 +114,7 @@
     static final WhiteBox WB = WhiteBox.getWhiteBox();
 
     @DontInline
-    static int invokeBasic() {
+    static int invokeExact() {
         try {
             return (int)mh.invokeExact();
         } catch (Throwable e) {
@@ -130,7 +130,7 @@
 
     public static void main(String[] args) throws Exception {
         for (int i = 0; i < 20_000; i++) {
-            int r = invokeBasic();
+            int r = invokeExact();
             if (r != 0) {
                 throw new Error(r + " != 0");
             }
@@ -142,7 +142,7 @@
         int exp = (instr != null) ? 1 : 0;
 
         for (int i = 0; i < 20_000; i++) {
-            if (invokeBasic() != exp) {
+            if (invokeExact() != exp) {
                 throw new Error();
             }
         }
@@ -150,7 +150,7 @@
         WB.clearInlineCaches();
 
         for (int i = 0; i < 20_000; i++) {
-            if (invokeBasic() != exp) {
+            if (invokeExact() != exp) {
                 throw new Error();
             }
         }
--- a/test/hotspot/jtreg/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,11 +26,11 @@
 import java.lang.invoke.MethodHandles.Lookup;
 import jdk.internal.vm.annotation.DontInline;
 import jdk.internal.vm.annotation.ForceInline;
+
 /**
  * Helper class to inject into java.lang.invoke that provides access to
  * package-private methods in this package.
  */
-
 public class MethodHandleHelper {
 
     private MethodHandleHelper() { }
@@ -79,29 +79,4 @@
     public static LambdaForm getLambdaForm(MethodHandle mh) {
         return mh.form;
     }
-
-    public static class NonInlinedReinvoker extends DelegatingMethodHandle {
-        private final MethodHandle target;
-
-        private NonInlinedReinvoker(MethodHandle target, LambdaForm lf) {
-            super(target.type(), lf);
-            this.target = target;
-        }
-        @Override
-        public MethodHandle getTarget() {
-            return target;
-        }
-
-        @Override
-        public MethodHandle asTypeUncached(MethodType newType) {
-            return asTypeCache = target.asType(newType);
-        }
-
-        public static MethodHandle make(MethodHandle target) {
-            LambdaForm lform = DelegatingMethodHandle.makeReinvokerForm(
-                    target, -1, DelegatingMethodHandle.class,
-                /*forceInline=*/false, DelegatingMethodHandle.NF_getTarget, null);
-            return new NonInlinedReinvoker(target, lform);
-        }
-    }
 }
--- a/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,7 @@
  * @test TestBasicLogOutput
  * @bug 8203370
  * @summary Ensure -XX:-JVMCIPrintProperties can be enabled and successfully prints expected output to stdout.
- * @requires vm.jvmci
+ * @requires vm.jvmci & !vm.graal.enabled & vm.compMode == "Xmixed"
  * @library /test/lib
  */
 
--- a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/FindUniqueConcreteMethodTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/FindUniqueConcreteMethodTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -79,7 +79,7 @@
         // overriden method
         result.add(new TestCase(true, SingleSubclass.class, "overridenMethod"));
         // private method
-        result.add(new TestCase(true, SingleSubclass.class, "privateMethod"));
+        result.add(new TestCase(InternalError.class, SingleSubclass.class, "privateMethod"));
         // protected method
         result.add(new TestCase(true, SingleSubclass.class, "protectedMethod"));
         // default(package-private) method
@@ -92,7 +92,7 @@
         // result.add(new TestCase(true, SingleImplementer.class,
         //                         SingleImplementerInterface.class, "defaultMethod"));
         // static method
-        result.add(new TestCase(false, SingleSubclass.class, "staticMethod"));
+        result.add(new TestCase(InternalError.class, SingleSubclass.class, "staticMethod"));
         // interface method
         result.add(new TestCase(false, MultipleSuperImplementers.class,
                                 DuplicateSimpleSingleImplementerInterface.class, "interfaceMethod"));
@@ -109,10 +109,21 @@
         HotSpotResolvedObjectType resolvedType = CompilerToVMHelper
                 .lookupTypeHelper(Utils.toJVMTypeSignature(tcase.receiver), getClass(),
                 /* resolve = */ true);
-        HotSpotResolvedJavaMethod concreteMethod = CompilerToVMHelper
-                .findUniqueConcreteMethod(resolvedType, testMethod);
-        Asserts.assertEQ(concreteMethod, tcase.isPositive ? testMethod : null,
-                "Unexpected concrete method for " + tcase.methodName);
+        if (tcase.exception != null) {
+            try {
+                HotSpotResolvedJavaMethod concreteMethod = CompilerToVMHelper
+                        .findUniqueConcreteMethod(resolvedType, testMethod);
+
+                Asserts.fail("Exception " + tcase.exception.getName() + " not thrown for " + tcase.methodName);
+            } catch (Throwable t) {
+                Asserts.assertEQ(t.getClass(), tcase.exception, "Wrong exception thrown for " + tcase.methodName);
+            }
+        } else {
+            HotSpotResolvedJavaMethod concreteMethod = CompilerToVMHelper
+                    .findUniqueConcreteMethod(resolvedType, testMethod);
+            Asserts.assertEQ(concreteMethod, tcase.isPositive ? testMethod : null,
+                    "Unexpected concrete method for " + tcase.methodName);
+        }
     }
 
     private static class TestCase {
@@ -120,23 +131,35 @@
         public final Class<?> holder;
         public final String methodName;
         public final boolean isPositive;
+        public final Class<?> exception;
 
         public TestCase(boolean isPositive, Class<?> clazz, Class<?> holder,
-                        String methodName) {
+                        String methodName, Class<?> exception) {
             this.receiver = clazz;
             this.methodName = methodName;
             this.isPositive = isPositive;
             this.holder = holder;
+            this.exception = exception;
+        }
+
+        public TestCase(boolean isPositive, Class<?> clazz, Class<?> holder,
+                        String methodName) {
+            this(isPositive, clazz, holder, methodName, null);
         }
 
         public TestCase(boolean isPositive, Class<?> clazz, String methodName) {
-            this(isPositive, clazz, clazz, methodName);
+            this(isPositive, clazz, clazz, methodName, null);
+        }
+
+        public TestCase(Class<?> exception, Class<?> clazz, String methodName) {
+            this(false, clazz, clazz, methodName, exception);
         }
 
         @Override
         public String toString() {
-            return String.format("CASE: receiver=%s, holder=%s, method=%s, isPositive=%s",
-                                 receiver.getName(), holder.getName(), methodName, isPositive);
+            return String.format("CASE: receiver=%s, holder=%s, method=%s, isPositive=%s, exception=%s",
+                                 receiver.getName(), holder.getName(), methodName, isPositive,
+                                 exception == null ? "<none>" : exception.getName());
         }
     }
 }
--- a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsCompilableTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/IsCompilableTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -24,7 +24,7 @@
 /**
  * @test
  * @bug 8136421
- * @requires vm.jvmci
+ * @requires vm.jvmci & vm.compMode == "Xmixed"
  * @library /test/lib /
  * @library ../common/patches
  * @modules java.base/jdk.internal.misc
--- a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -25,11 +25,11 @@
  * @test
  * @bug 8136421
  *
- * @requires vm.jvmci
+ * @requires vm.jvmci & vm.compMode == "Xmixed"
  * @requires vm.opt.final.EliminateAllocations == true
  *
  * @comment no "-Xcomp -XX:-TieredCompilation" combination allowed until JDK-8140018 is resolved
- * @requires vm.compMode != "Xcomp" | vm.opt.TieredCompilation == null | vm.opt.TieredCompilation == true
+ * @requires vm.opt.TieredCompilation == null | vm.opt.TieredCompilation == true
  *
  * @library / /test/lib
  * @library ../common/patches
@@ -44,7 +44,7 @@
  * @build jdk.internal.vm.ci/jdk.vm.ci.hotspot.CompilerToVMHelper sun.hotspot.WhiteBox
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main/othervm -Xmixed -Xbatch -Xbootclasspath/a:.
+ * @run main/othervm -Xbatch -Xbootclasspath/a:.
  *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   -XX:CompileCommand=exclude,compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest::check
@@ -56,7 +56,7 @@
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.materializeFirst=true
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.invalidate=false
  *                   compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest
- * @run main/othervm -Xmixed -Xbatch -Xbootclasspath/a:.
+ * @run main/othervm -Xbatch -Xbootclasspath/a:.
  *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   -XX:CompileCommand=exclude,compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest::check
@@ -68,7 +68,7 @@
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.materializeFirst=false
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.invalidate=false
  *                   compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest
- * @run main/othervm -Xmixed -Xbatch -Xbootclasspath/a:.
+ * @run main/othervm -Xbatch -Xbootclasspath/a:.
  *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   -XX:CompileCommand=exclude,compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest::check
@@ -80,7 +80,7 @@
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.materializeFirst=true
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.invalidate=true
  *                   compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest
- * @run main/othervm -Xmixed -Xbatch -Xbootclasspath/a:.
+ * @run main/othervm -Xbatch -Xbootclasspath/a:.
  *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   -XX:CompileCommand=exclude,compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest::check
--- a/test/hotspot/jtreg/compiler/jvmci/events/JvmciNotifyBootstrapFinishedEventTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/events/JvmciNotifyBootstrapFinishedEventTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -24,7 +24,7 @@
 /**
  * @test
  * @bug 8156034
- * @requires vm.jvmci & !vm.graal.enabled
+ * @requires vm.jvmci & !vm.graal.enabled & vm.compMode == "Xmixed"
  * @library / /test/lib
  * @library ../common/patches
  * @modules java.base/jdk.internal.misc
--- a/test/hotspot/jtreg/compiler/jvmci/events/JvmciNotifyInstallEventTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/compiler/jvmci/events/JvmciNotifyInstallEventTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 8136421
- * @requires vm.jvmci & !vm.graal.enabled
+ * @requires vm.jvmci & !vm.graal.enabled & vm.compMode == "Xmixed"
  * @library / /test/lib
  * @library ../common/patches
  * @modules java.base/jdk.internal.misc
@@ -47,11 +47,11 @@
  *      compiler.jvmci.common.JVMCIHelpers$EmptyCompilationRequestResult
  *      compiler.jvmci.common.JVMCIHelpers$EmptyVMEventListener
  * @run main/othervm -XX:+UnlockExperimentalVMOptions
- *     -Djvmci.Compiler=EmptyCompiler -Xbootclasspath/a:. -Xmixed
+ *     -Djvmci.Compiler=EmptyCompiler -Xbootclasspath/a:.
  *     -XX:+UseJVMCICompiler -XX:-BootstrapJVMCI
  *     compiler.jvmci.events.JvmciNotifyInstallEventTest
  * @run main/othervm -XX:+UnlockExperimentalVMOptions
- *     -Djvmci.Compiler=EmptyCompiler -Xbootclasspath/a:. -Xmixed
+ *     -Djvmci.Compiler=EmptyCompiler -Xbootclasspath/a:.
  *     -XX:+UseJVMCICompiler -XX:-BootstrapJVMCI -XX:JVMCINMethodSizeLimit=0
  *     compiler.jvmci.events.JvmciNotifyInstallEventTest
  */
--- a/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java	Wed Jun 12 10:02:49 2019 +0530
@@ -55,6 +55,8 @@
     checkValidMinInitialHeapCombinations(gcflag);
     checkInvalidInitialMaxHeapCombinations(gcflag);
     checkValidInitialMaxHeapCombinations(gcflag);
+    checkInvalidMinMaxHeapCombinations(gcflag);
+    checkValidMinMaxHeapCombinations(gcflag);
   }
 
   public static void checkMinInitialErgonomics(String gcflag) throws Exception {
@@ -71,18 +73,33 @@
 
     // -Xms is not set
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize }, values, -1, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=" + smallValue }, values, smallValue, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=" + largeValue }, values, largeValue, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=0" }, values, -1, -1);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:InitialHeapSize=" + smallValue }, values, -1, smallValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:InitialHeapSize=" + largeValue }, values, -1, largeValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:InitialHeapSize=0" }, values, -1, -1);
+    // Some extra checks when both are set.
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=" + smallValue, "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=" + smallValue, "-XX:InitialHeapSize=" + largeValue }, values, smallValue, largeValue);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-XX:MinHeapSize=" + largeValue, "-XX:InitialHeapSize=" + largeValue }, values, largeValue, largeValue);
 
     // -Xms is set to zero
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0" }, values, -1, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=" + smallValue }, values, smallValue, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=" + largeValue }, values, largeValue, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=0" }, values, -1, -1);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:InitialHeapSize=" + smallValue }, values, -1, smallValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:InitialHeapSize=" + largeValue }, values, -1, largeValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:InitialHeapSize=0" }, values, -1, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=" + smallValue, "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=" + smallValue, "-XX:InitialHeapSize=" + largeValue }, values, smallValue, largeValue);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms0", "-XX:MinHeapSize=" + largeValue, "-XX:InitialHeapSize=" + largeValue }, values, largeValue, largeValue);
 
     // -Xms is set to small value
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue }, values, -1, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue, "-XX:MinHeapSize=" + smallValue }, values, smallValue, smallValue);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue, "-XX:MinHeapSize=0" }, values, -1, smallValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue, "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue, "-XX:InitialHeapSize=" + largeValue }, values, smallValue, largeValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + smallValue, "-XX:InitialHeapSize=0" }, values, smallValue, -1);
@@ -90,6 +107,7 @@
     // -Xms is set to large value
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + largeValue }, values, largeValue, largeValue);
     checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + largeValue, "-XX:InitialHeapSize=0" }, values, largeValue, -1);
+    checkErgonomics(new String[] { gcflag, "-Xmx" + maxHeapSize, "-Xms" + largeValue, "-XX:MinHeapSize=0" }, values, -1, largeValue);
   }
 
   private static long align_up(long value, long alignment) {
@@ -116,6 +134,9 @@
   private static void checkInvalidMinInitialHeapCombinations(String gcflag) throws Exception {
     expectError(new String[] { gcflag, "-XX:InitialHeapSize=1023K", "-version" });
     expectError(new String[] { gcflag, "-Xms64M", "-XX:InitialHeapSize=32M", "-version" });
+    expectError(new String[] { gcflag, "-XX:MinHeapSize=1023K", "-version" });
+    expectError(new String[] { gcflag, "-Xms4M", "-XX:MinHeapSize=8M", "-version" });
+    expectError(new String[] { gcflag, "-XX:MinHeapSize=8M -XX:InitialHeapSize=4m" });
   }
 
   private static void checkValidMinInitialHeapCombinations(String gcflag) throws Exception {
@@ -123,8 +144,13 @@
     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-Xms4M", "-version" });
     expectValid(new String[] { gcflag, "-Xms4M", "-XX:InitialHeapSize=8M", "-version" });
     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-Xms8M", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MinHeapSize=1024K", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MinHeapSize=8M", "-Xms4M", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MinHeapSize=8M", "-Xms8M", "-version" });
+    expectValid(new String[] { gcflag, "-Xms8M", "-XX:MinHeapSize=4M", "-version" });
     // the following is not an error as -Xms sets both minimal and initial heap size
     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=4M", "-Xms8M", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MinHeapSize=4M", "-Xms8M", "-version" });
   }
 
   private static void checkInvalidInitialMaxHeapCombinations(String gcflag) throws Exception {
@@ -133,6 +159,12 @@
     expectError(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-XX:MaxHeapSize=4M", "-version" });
   }
 
+  private static void checkInvalidMinMaxHeapCombinations(String gcflag) throws Exception {
+    expectError(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:MinHeapSize=8M", "-version" });
+    expectError(new String[] { gcflag, "-XX:MinHeapSize=8M", "-XX:MaxHeapSize=4M", "-version" });
+  }
+
+
   private static void checkValidInitialMaxHeapCombinations(String gcflag) throws Exception {
     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=4M", "-XX:MaxHeapSize=8M", "-version" });
     expectValid(new String[] { gcflag, "-XX:MaxHeapSize=8M", "-XX:InitialHeapSize=4M", "-version" });
@@ -141,6 +173,14 @@
     expectValid(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:InitialHeapSize=0M", "-version" });
   }
 
+  private static void checkValidMinMaxHeapCombinations(String gcflag) throws Exception {
+    expectValid(new String[] { gcflag, "-XX:MinHeapSize=4M", "-XX:MaxHeapSize=8M", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MaxHeapSize=8M", "-XX:MinHeapSize=4M", "-version" });
+    expectValid(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:MinHeapSize=4M", "-version" });
+    // a value of "0" for min heap size means auto-detect
+    expectValid(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:MinHeapSize=0M", "-version" });
+  }
+
   private static long valueAfter(String source, String match) {
     int start = source.indexOf(match) + match.length();
     String tail = source.substring(start).split(" ")[0];
@@ -294,4 +334,3 @@
     expect(flags, false, false, 0);
   }
 }
-
--- a/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java	Wed Jun 12 10:02:49 2019 +0530
@@ -57,7 +57,7 @@
     public static void main(String[] args) throws Exception {
         ArrayList<String> baseargs = new ArrayList<>(Arrays.asList("-Xms256M",
                                                                    "-Xmx256M",
-                                                                   "-Xlog:gc*",
+                                                                   "-Xlog:gc*,stringtable*=debug:gc.log",
                                                                    "-XX:NativeMemoryTracking=summary",
                                                                    "-XX:+UnlockDiagnosticVMOptions",
                                                                    "-XX:+PrintNMTStatistics" ));
@@ -95,9 +95,19 @@
                     lastString = (BaseName + i).intern();
                 }
                 if (++iterations % 5 == 0) {
-                   System.gc();
+                    System.gc();
                 }
             }
+            // Do one last GC and sleep to give ServiceThread a chance to run.
+            System.out.println("One last gc");
+            System.gc();
+            for (int i = 0; i < 100; i++) {
+                try {
+                    Thread.sleep(10);
+                } catch (InterruptedException ex) {
+                }
+            }
+            System.out.println("End of test");
         }
     }
 }
--- a/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -73,7 +73,7 @@
 
         // Subtract 1 from class's major version.  The class should fail to load
         // because its major_version does not match the JVM current version.
-        int prev_major_version = Runtime.version().feature() - 1;
+        int prev_major_version = (klassbuf[6] << 8 | klassbuf[7]) - 1;
         klassbuf[6] = (byte)((prev_major_version >> 8) & 0xff);
         klassbuf[7] = (byte)(prev_major_version & 0xff);
         try {
@@ -81,8 +81,8 @@
             throw new RuntimeException("UnsupportedClassVersionError exception not thrown");
         } catch (java.lang.UnsupportedClassVersionError e) {
             if (!e.getMessage().contains("compiled with preview features that are unsupported")) {
-                throw new RuntimeException(
-                    "Wrong UnsupportedClassVersionError exception: " + e.getMessage());
+              throw new RuntimeException(
+                  "Wrong UnsupportedClassVersionError exception: " + e.getMessage());
             }
         }
 
@@ -97,10 +97,10 @@
                 "Unexpected UnsupportedClassVersionError exception thrown: " + e.getMessage());
         }
 
-        // Check that a class with a recent older major version and a non-zero
-        // minor version fails to load.
+        // Check that a class with a recent older major version > JDK-11 and a minor version
+        // that is neither 0 nor 65535 fails to load.
         klassbuf[6] = 0;
-        klassbuf[7] = 53;
+        klassbuf[7] = 56;
         klassbuf[4] = 0;
         klassbuf[5] = 2;
         try {
--- a/test/hotspot/jtreg/runtime/appcds/GraalWithLimitedMetaspace.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/runtime/appcds/GraalWithLimitedMetaspace.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
  * @test
  * @summary Test dumping with limited metaspace with loading of JVMCI related classes.
  *          VM should not crash but CDS dump will abort upon failure in allocating metaspace.
- * @requires vm.cds & vm.graal.enabled
+ * @requires vm.cds & vm.graal.enabled & vm.compMode == "Xmixed"
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  *          java.management
@@ -90,6 +90,8 @@
             "-XX:DumpLoadedClassList=" + CLASSLIST_FILE,
             // trigger JVMCI runtime init so that JVMCI classes will be
             // included in the classlist
+            "-XX:+UnlockExperimentalVMOptions",
+            "-XX:+EnableJVMCI",
             "-XX:+EagerJVMCI",
             "-cp",
             TESTJAR,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/serviceability/dcmd/compiler/CodeHeapAnalyticsParams.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import jdk.test.lib.dcmd.PidJcmdExecutor;
+
+/*
+ * @test CodeHeapAnalyticsParams
+ * @key jcmd
+ * @summary Test the Compiler.CodeHeap_Analytics command
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @run driver CodeHeapAnalyticsParams
+ */
+
+public class CodeHeapAnalyticsParams {
+
+    public static void main(String args[]) throws Exception {
+        PidJcmdExecutor executor = new PidJcmdExecutor();
+        executor.execute("Compiler.CodeHeap_Analytics all 1").shouldHaveExitValue(0);
+        executor.execute("Compiler.CodeHeap_Analytics all 0").shouldHaveExitValue(1);
+        executor.execute("Compiler.CodeHeap_Analytics all k").shouldHaveExitValue(1);
+    }
+}
--- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/multithrd/tc02x004.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/multithrd/tc02x004.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
 
 package nsk.jdi.BScenarios.multithrd;
 
+import jdk.test.lib.Utils;
 import nsk.share.*;
 import nsk.share.jpda.*;
 import nsk.share.jdi.*;
@@ -95,7 +96,7 @@
         ArgumentHandler argHandler = new ArgumentHandler(argv);
         log = new Log(out, argHandler);
 
-        waitTime = argHandler.getWaitTime() * 60000;
+        waitTime = Utils.adjustTimeout(argHandler.getWaitTime() * 60000);
 
         Binder binder = new Binder(argHandler, log);
         debugee = binder.bindToDebugee(debugeeName);
@@ -114,6 +115,7 @@
         }
         display("Test finished. exitStatus = " + exitStatus);
 
+        debugee.endDebugee();
         return exitStatus;
     }
 
--- a/test/jaxp/javax/xml/jaxp/unittest/transform/ProcessXSLT.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jaxp/javax/xml/jaxp/unittest/transform/ProcessXSLT.java	Wed Jun 12 10:02:49 2019 +0530
@@ -145,15 +145,12 @@
    */
     public static void main(String argv[]) {
 
-        // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
         boolean doStackDumpOnError = false;
         boolean doDiag = false;
         boolean setQuietMode = false;
         String msg = null;
         boolean isSecureProcessing = false;
 
-        // Runtime.getRuntime().traceMethodCalls(false);
-        // Runtime.getRuntime().traceInstructions(false);
         /**
          * The default diagnostic writer...
          */
--- a/test/jdk/com/sun/net/httpserver/MissingTrailingSpace.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/MissingTrailingSpace.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,12 @@
  * @test
  * @bug 8068795
  * @summary HttpServer missing tailing space for some response codes
+ * @run main MissingTrailingSpace
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true MissingTrailingSpace
  * @author lev.priima@oracle.com
  */
 
+import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.io.InputStreamReader;
 import java.io.IOException;
@@ -47,7 +50,8 @@
     private static final String someContext = "/context";
 
     public static void main(String[] args) throws Exception {
-        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        HttpServer server = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
         try {
             server.setExecutor(Executors.newFixedThreadPool(1));
             server.createContext(someContext, new HttpHandler() {
@@ -68,7 +72,7 @@
             System.out.println("Server started at port "
                                + server.getAddress().getPort());
 
-            runRawSocketHttpClient("localhost", server.getAddress().getPort());
+            runRawSocketHttpClient(loopback, server.getAddress().getPort());
         } finally {
             ((ExecutorService)server.getExecutor()).shutdown();
             server.stop(0);
@@ -76,7 +80,7 @@
         System.out.println("Server finished.");
     }
 
-    static void runRawSocketHttpClient(String hostname, int port)
+    static void runRawSocketHttpClient(InetAddress address, int port)
         throws Exception
     {
         Socket socket = null;
@@ -84,7 +88,7 @@
         BufferedReader reader = null;
         final String CRLF = "\r\n";
         try {
-            socket = new Socket(hostname, port);
+            socket = new Socket(address, port);
             writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream()));
             System.out.println("Client connected by socket: " + socket);
@@ -93,7 +97,7 @@
             writer.print("User-Agent: Java/"
                 + System.getProperty("java.version")
                 + CRLF);
-            writer.print("Host: " + hostname + CRLF);
+            writer.print("Host: " + address.getHostName() + CRLF);
             writer.print("Accept: */*" + CRLF);
             writer.print("Connection: keep-alive" + CRLF);
             writer.print(CRLF); // Important, else the server will expect that
@@ -140,4 +144,3 @@
         System.out.println("Client finished." );
     }
 }
-
--- a/test/jdk/com/sun/net/httpserver/Test1.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test1.java	Wed Jun 12 10:02:49 2019 +0530
@@ -27,6 +27,7 @@
  * @library /test/lib
  * @build jdk.test.lib.net.SimpleSSLContext
  * @run main/othervm Test1
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test1
  * @run main/othervm -Djdk.net.usePlainSocketImpl Test1
  * @run main/othervm -Dsun.net.httpserver.maxReqTime=10 Test1
  * @run main/othervm -Dsun.net.httpserver.nodelay=true Test1
@@ -40,6 +41,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /* basic http/s connectivity test
  * Tests:
@@ -64,7 +66,8 @@
         try {
             String root = System.getProperty ("test.src")+ "/docs";
             System.out.print ("Test1: ");
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress (loopback, 0);
             s1 = HttpServer.create (addr, 0);
             if (s1 instanceof HttpsServer) {
                 throw new RuntimeException ("should not be httpsserver");
@@ -104,8 +107,13 @@
     }
 
     static void test (boolean fixedLen, String protocol, String root, int port, String f, int size) throws Exception {
-        URL url = new URL (protocol+"://localhost:"+port+"/test1/"+f);
-        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
+        URL url = URIBuilder.newBuilder()
+                 .scheme(protocol)
+                 .loopback()
+                 .port(port)
+                 .path("/test1/"+f)
+                 .toURL();
+        HttpURLConnection urlc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
         if (urlc instanceof HttpsURLConnection) {
             HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
             urlcs.setHostnameVerifier (new HostnameVerifier () {
--- a/test/jdk/com/sun/net/httpserver/Test10.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test10.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 7005016
  * @summary  pit jdk7 b121  sqe test jhttp/HttpServer150013 failing
  * @run main/othervm -Dsun.net.httpserver.clockTick=1000 -Dsun.net.httpserver.idleInterval=3 Test10
+ * @run main/othervm -Dsun.net.httpserver.clockTick=1000 -Dsun.net.httpserver.idleInterval=3
+ *                   -Djava.net.preferIPv6Addresses Test10
  */
 
 import com.sun.net.httpserver.*;
@@ -42,7 +44,8 @@
     public static void main (String[] args) throws Exception {
         System.out.print ("Test10: ");
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         int port = server.getAddress().getPort();
         HttpContext c2 = server.createContext ("/test", handler);
@@ -78,7 +81,7 @@
     public static void doClient (int port) throws Exception {
         String s = "GET /test/1.html HTTP/1.1\r\n\r\n";
 
-        Socket socket = new Socket ("localhost", port);
+        Socket socket = new Socket (InetAddress.getLoopbackAddress(), port);
         OutputStream os = socket.getOutputStream();
         os.write (s.getBytes());
         socket.setSoTimeout (10 * 1000);
--- a/test/jdk/com/sun/net/httpserver/Test11.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test11.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,12 +25,16 @@
  * @test
  * @bug 6270015
  * @summary  Light weight HTTP server
+ * @library /test/lib
+ * @run main Test11
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test11
  */
 
 import java.net.*;
 import java.util.concurrent.*;
 import java.io.*;
 import com.sun.net.httpserver.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class Test11 {
     static class Handler implements HttpHandler {
@@ -51,7 +55,8 @@
 
     public static void main (String[] args) throws Exception {
         System.out.print ("Test 11: ");
-        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        HttpServer server = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
         ExecutorService s = Executors.newCachedThreadPool();
         try {
             HttpContext ctx = server.createContext (
@@ -59,9 +64,13 @@
             );
             s =  Executors.newCachedThreadPool();
             server.start ();
-            URL url = new URL ("http://localhost:" + server.getAddress().getPort()+
-                    "/Foo/bar/test.html");
-            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
+            URL url = URIBuilder.newBuilder()
+                      .scheme("http")
+                      .loopback()
+                      .port(server.getAddress().getPort())
+                      .path("/Foo/bar/test.html")
+                      .toURL();
+            HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
             int r = urlc.getResponseCode();
             if (r == 200) {
                 throw new RuntimeException ("wrong response received");
--- a/test/jdk/com/sun/net/httpserver/Test12.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test12.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
  * @library /test/lib
  * @build jdk.test.lib.net.SimpleSSLContext
  * @run main/othervm Test12
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test12
  * @summary Light weight HTTP server
  */
 
@@ -37,6 +38,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /* basic http/s connectivity test
  * Tests:
@@ -56,7 +58,8 @@
         try {
             String root = System.getProperty ("test.src")+ "/docs";
             System.out.print ("Test12: ");
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             s1 = HttpServer.create (addr, 0);
             s2 = HttpsServer.create (addr, 0);
             HttpHandler h = new FileServerHandler (root);
@@ -130,8 +133,13 @@
 
         public void run () {
             try {
-                URL url = new URL (protocol+"://localhost:"+port+"/test1/"+f);
-                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
+                URL url = URIBuilder.newBuilder()
+                          .scheme(protocol)
+                          .loopback()
+                          .port(port)
+                          .path("/test1/"+f)
+                          .toURL();
+                HttpURLConnection urlc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                 if (urlc instanceof HttpsURLConnection) {
                     HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
                     urlcs.setHostnameVerifier (new HostnameVerifier () {
--- a/test/jdk/com/sun/net/httpserver/Test13.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test13.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
  * @library /test/lib
  * @build jdk.test.lib.net.SimpleSSLContext
  * @run main/othervm Test13
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test13
  * @summary Light weight HTTP server
  */
 
@@ -38,6 +39,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /* basic http/s connectivity test
  * Tests:
@@ -61,10 +63,12 @@
         ha.setLevel(Level.ALL);
         l.setLevel(Level.ALL);
         l.addHandler(ha);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+
         try {
             String root = System.getProperty ("test.src")+ "/docs";
             System.out.print ("Test13: ");
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             s1 = HttpServer.create (addr, 0);
             s2 = HttpsServer.create (addr, 0);
             HttpHandler h = new FileServerHandler (root);
@@ -136,8 +140,13 @@
 
         public void run () {
             try {
-                URL url = new URL (protocol+"://localhost:"+port+"/test1/"+f);
-                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
+                URL url = URIBuilder.newBuilder()
+                          .scheme(protocol)
+                          .loopback()
+                          .port(port)
+                          .path("/test1/"+f)
+                          .toURL();
+                HttpURLConnection urlc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                 if (urlc instanceof HttpsURLConnection) {
                     HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
                     urlcs.setHostnameVerifier (new HostnameVerifier () {
--- a/test/jdk/com/sun/net/httpserver/Test14.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test14.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,9 @@
  * @test
  * @bug 6270015
  * @summary  Light weight HTTP server
+ * @library /test/lib
+ * @run main Test14
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test14
  */
 
 import com.sun.net.httpserver.*;
@@ -36,6 +39,7 @@
 import java.security.*;
 import javax.security.auth.callback.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test filters
@@ -77,7 +81,8 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
 
@@ -94,9 +99,14 @@
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+                  .scheme("http")
+                  .loopback()
+                  .port(server.getAddress().getPort())
+                  .path("/test/foo.html")
+                  .toURL();
         System.out.print ("Test14: " );
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         InputStream is = urlc.getInputStream();
         int x = 0;
         String output="";
--- a/test/jdk/com/sun/net/httpserver/Test2.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,9 @@
  * @test
  * @bug 6270015
  * @summary  Light weight HTTP server
+ * @library /test/lib
+ * @run main Test2
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test2
  */
 
 import com.sun.net.httpserver.*;
@@ -36,6 +39,7 @@
 import java.security.*;
 import javax.security.auth.callback.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test authentication
@@ -45,7 +49,8 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         BasicAuthenticator a = new BasicAuthenticator ("foobar@test.realm") {
@@ -60,9 +65,15 @@
         server.start ();
         java.net.Authenticator.setDefault (new MyAuthenticator());
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+
         System.out.print ("Test2: " );
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         InputStream is = urlc.getInputStream();
         int c = 0;
         while (is.read()!= -1) {
--- a/test/jdk/com/sun/net/httpserver/Test3.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test3.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 6270015
  * @summary  Light weight HTTP server
  * @run main/othervm -Dsun.net.httpserver.idleInterval=4 Test3
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dsun.net.httpserver.idleInterval=4 Test3
  */
 
 import com.sun.net.httpserver.*;
@@ -48,7 +50,8 @@
     public static void main (String[] args) throws Exception {
         System.out.print ("Test3: ");
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         int port = server.getAddress().getPort();
         HttpContext c2 = server.createContext ("/test", handler);
@@ -135,7 +138,7 @@
         "GET /test/4.html HTTP/1.1\r\nContent-length: 10\r\n"+
         "\r\n"+body4;
 
-        Socket socket = new Socket ("localhost", port);
+        Socket socket = new Socket (InetAddress.getLoopbackAddress(), port);
         OutputStream os = socket.getOutputStream();
         os.write (s.getBytes());
         InputStream is = socket.getInputStream();
--- a/test/jdk/com/sun/net/httpserver/Test4.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test4.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 6270015
  * @summary  Light weight HTTP server
  * @run main/othervm -Dsun.net.httpserver.idleInterval=4 Test4
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dsun.net.httpserver.idleInterval=4 Test4
  */
 
 import com.sun.net.httpserver.*;
@@ -46,7 +48,8 @@
     public static void main (String[] args) throws Exception {
         System.out.print ("Test4: ");
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         int port = server.getAddress().getPort();
         HttpContext c2 = server.createContext ("/test", handler);
@@ -133,7 +136,7 @@
         "GET /test/4.html HTTP/1.1\r\nContent-length: 10\r\n"+
         "\r\n"+body4;
 
-        Socket socket = new Socket ("localhost", port);
+        Socket socket = new Socket (InetAddress.getLoopbackAddress(), port);
         OutputStream os = socket.getOutputStream();
         os.write (s.getBytes());
         InputStream is = socket.getInputStream();
--- a/test/jdk/com/sun/net/httpserver/Test5.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test5.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 6270015
  * @summary  Light weight HTTP server
  * @run main/othervm -Dsun.net.httpserver.idleInterval=4 Test5
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dsun.net.httpserver.idleInterval=4 Test5
  */
 
 import com.sun.net.httpserver.*;
@@ -47,7 +49,8 @@
     public static void main (String[] args) throws Exception {
         System.out.print ("Test5: ");
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         int port = server.getAddress().getPort();
         HttpContext c2 = server.createContext ("/test", handler);
@@ -132,7 +135,7 @@
         "GET /test/4.html HTTP/1.1\r\nContent-length: 10\r\n"+
         "\r\n"+body4;
 
-        Socket socket = new Socket ("localhost", port);
+        Socket socket = new Socket (InetAddress.getLoopbackAddress(), port);
         OutputStream os = socket.getOutputStream();
         os.write (s.getBytes());
         InputStream is = socket.getInputStream();
--- a/test/jdk/com/sun/net/httpserver/Test6.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test6.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,9 @@
  * @test
  * @bug 6270015
  * @summary  Light weight HTTP server
+ * @library /test/lib
+ * @run main Test6
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test6
  */
 
 import com.sun.net.httpserver.*;
@@ -36,6 +39,7 @@
 import java.security.*;
 import javax.security.auth.callback.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test POST large file via chunked encoding (unusually small chunks)
@@ -45,16 +49,23 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+
         System.out.print ("Test6: " );
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.setDoOutput (true);
         urlc.setRequestMethod ("POST");
         urlc.setChunkedStreamingMode (32); // small chunks
--- a/test/jdk/com/sun/net/httpserver/Test7.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test7.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,10 @@
 /**
  * @test
  * @bug 6270015
+ * @library /test/lib
  * @summary  Light weight HTTP server
+ * @run main Test7
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test7
  */
 
 import com.sun.net.httpserver.*;
@@ -36,6 +39,7 @@
 import java.security.*;
 import javax.security.auth.callback.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test POST large file via chunked encoding (large chunks)
@@ -45,16 +49,22 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+                  .scheme("http")
+                  .loopback()
+                  .port(server.getAddress().getPort())
+                  .path("/test/foo.html")
+                  .toURL();
         System.out.print ("Test7: " );
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.setDoOutput (true);
         urlc.setRequestMethod ("POST");
         urlc.setChunkedStreamingMode (16 * 1024); // big chunks
--- a/test/jdk/com/sun/net/httpserver/Test7a.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test7a.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
  * @test
  * @bug 6270015
  * @library /test/lib
- * @build jdk.test.lib.net.SimpleSSLContext
+ * @build jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.URIBuilder
  * @run main/othervm Test7a
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test7a
  * @summary Light weight HTTP server
  */
 
@@ -37,6 +38,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test POST large file via chunked encoding (large chunks)
@@ -51,7 +53,8 @@
         //h.setLevel (Level.ALL);
         //log.addHandler (h);
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpsServer server = HttpsServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
@@ -60,9 +63,15 @@
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("https://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+            .scheme("https")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+
         System.out.print ("Test7a: " );
-        HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection ();
+        HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.setDoOutput (true);
         urlc.setRequestMethod ("POST");
         urlc.setChunkedStreamingMode (16 * 1024); // big chunks
--- a/test/jdk/com/sun/net/httpserver/Test8.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test8.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,10 @@
 /**
  * @test
  * @bug 6270015
+ * @library /test/lib
  * @summary  Light weight HTTP server
+ * @run main Test8
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test8
  */
 
 import com.sun.net.httpserver.*;
@@ -36,6 +39,7 @@
 import java.security.*;
 import javax.security.auth.callback.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test POST large file via fixed len encoding
@@ -45,16 +49,23 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+
         System.out.print ("Test8: " );
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.setDoOutput (true);
         urlc.setRequestMethod ("POST");
         OutputStream os = new BufferedOutputStream (urlc.getOutputStream());
--- a/test/jdk/com/sun/net/httpserver/Test8a.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test8a.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
  * @test
  * @bug 6270015
  * @library /test/lib
- * @build jdk.test.lib.net.SimpleSSLContext
+ * @build jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.URIBuilder
  * @run main/othervm Test8a
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test8a
  * @summary Light weight HTTP server
  */
 
@@ -37,6 +38,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /**
  * Test POST large file via fixed len encoding
@@ -54,7 +56,8 @@
         ExecutorService executor = null;
         try {
             Handler handler = new Handler();
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             server = HttpsServer.create (addr, 0);
             HttpContext ctx = server.createContext ("/test", handler);
             executor = Executors.newCachedThreadPool();
@@ -63,9 +66,15 @@
             server.setExecutor (executor);
             server.start ();
 
-            URL url = new URL ("https://localhost:"+server.getAddress().getPort()+"/test/foo.html");
+            URL url = URIBuilder.newBuilder()
+                .scheme("https")
+                .loopback()
+                .port(server.getAddress().getPort())
+                .path("/test/foo.html")
+                .toURL();
+
             System.out.print ("Test8a: " );
-            HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection ();
+            HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection(Proxy.NO_PROXY);
             urlc.setDoOutput (true);
             urlc.setRequestMethod ("POST");
             urlc.setHostnameVerifier (new DummyVerifier());
--- a/test/jdk/com/sun/net/httpserver/Test9.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test9.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
  * @test
  * @bug 6270015
  * @library /test/lib
- * @build jdk.test.lib.net.SimpleSSLContext
+ * @build jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.URIBuilder
  * @run main/othervm Test9
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test9
  * @summary Light weight HTTP server
  */
 
@@ -37,6 +38,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /* Same as Test1 but requests run in parallel.
  */
@@ -53,7 +55,8 @@
         try {
             String root = System.getProperty ("test.src")+ "/docs";
             System.out.print ("Test9: ");
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             s1 = HttpServer.create (addr, 0);
             s2 = HttpsServer.create (addr, 0);
             HttpHandler h = new FileServerHandler (root);
@@ -137,8 +140,14 @@
 
         public void run () {
             try {
-                URL url = new URL (protocol+"://localhost:"+port+"/test1/"+f);
-                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
+                URL url = URIBuilder.newBuilder()
+                    .scheme(protocol)
+                    .loopback()
+                    .port(port)
+                    .path("/test1/" + f)
+                    .toURL();
+
+                HttpURLConnection urlc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                 if (urlc instanceof HttpsURLConnection) {
                     HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
                     urlcs.setHostnameVerifier (new HostnameVerifier () {
@@ -185,7 +194,8 @@
                 String orig = root + "/" + f;
                 compare (new File(orig), temp);
                 temp.delete();
-            } catch (IOException e) {
+            } catch (Exception e) {
+                e.printStackTrace();
                 error = true;
             }
         }
--- a/test/jdk/com/sun/net/httpserver/Test9a.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/Test9a.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
  * @test
  * @bug 6270015
  * @library /test/lib
- * @build jdk.test.lib.net.SimpleSSLContext
+ * @build jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.URIBuilder
  * @run main/othervm Test9a
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test9a
  * @summary Light weight HTTP server
  */
 
@@ -37,6 +38,7 @@
 import java.net.*;
 import javax.net.ssl.*;
 import jdk.test.lib.net.SimpleSSLContext;
+import jdk.test.lib.net.URIBuilder;
 
 /* Same as Test1 but requests run in parallel.
  */
@@ -53,7 +55,8 @@
         try {
             String root = System.getProperty ("test.src")+ "/docs";
             System.out.print ("Test9a: ");
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             server = HttpsServer.create (addr, 0);
             HttpHandler h = new FileServerHandler (root);
             HttpContext c1 = server.createContext ("/test1", h);
@@ -131,8 +134,14 @@
 
         public void run () {
             try {
-                URL url = new URL (protocol+"://localhost:"+port+"/test1/"+f);
-                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
+                URL url = URIBuilder.newBuilder()
+                    .scheme(protocol)
+                    .loopback()
+                    .port(port)
+                    .path("/test1/" + f)
+                    .toURL();
+
+                HttpURLConnection urlc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                 if (urlc instanceof HttpsURLConnection) {
                     HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
                     urlcs.setHostnameVerifier (new HostnameVerifier () {
@@ -179,7 +188,7 @@
                 String orig = root + "/" + f;
                 compare (new File(orig), temp);
                 temp.delete();
-            } catch (IOException e) {
+            } catch (Exception e) {
                 e.printStackTrace();
                 error = true;
             }
--- a/test/jdk/com/sun/net/httpserver/TestLogging.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/TestLogging.java	Wed Jun 12 10:02:49 2019 +0530
@@ -26,6 +26,8 @@
  * @bug 6422914
  * @library /test/lib
  * @summary change httpserver exception printouts
+ * @run main TestLogging
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true TestLogging
  */
 
 import com.sun.net.httpserver.*;
@@ -49,7 +51,8 @@
         try {
             System.out.print ("Test9: ");
             String root = System.getProperty ("test.src")+ "/docs";
-            InetSocketAddress addr = new InetSocketAddress (0);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            InetSocketAddress addr = new InetSocketAddress(loopback, 0);
             Logger logger = Logger.getLogger ("com.sun.net.httpserver");
             logger.setLevel (Level.ALL);
             Handler h1 = new ConsoleHandler ();
@@ -70,9 +73,9 @@
                 .loopback()
                 .port(p1)
                 .path("/test1/smallfile.txt")
-                .toURLUnchecked();
+                .toURL();
             System.out.println("URL: " + url);
-            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
+            HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
             InputStream is = urlc.getInputStream();
             while (is.read() != -1) ;
             is.close();
--- a/test/jdk/com/sun/net/httpserver/bugs/B6339483.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6339483.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,9 @@
  * @test
  * @bug 6339483
  * @summary  NullPointerException when creating a HttpContext with no handler
+ * @library /test/lib
+ * @run main B6339483
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6339483
  */
 
 import com.sun.net.httpserver.*;
@@ -36,19 +39,26 @@
 import java.security.*;
 import java.security.cert.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6339483 {
 
     public static void main (String[] args) throws Exception {
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test");
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             int c = 0;
--- a/test/jdk/com/sun/net/httpserver/bugs/B6341616.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6341616.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,9 @@
 /**
  * @test
  * @bug 6341616
+ * @library /test/lib
+ * @run main B6341616
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6341616
  * @summary  Server doesnt send response if there is a RuntimeException in validate of BasicAuthFilter
  */
 
@@ -36,12 +39,14 @@
 import java.security.*;
 import java.security.cert.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6341616 {
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         BasicAuthenticator filter = new BasicAuthenticator ("foobar@test.realm") {
@@ -56,8 +61,13 @@
         server.start ();
         java.net.Authenticator.setDefault (new MyAuthenticator());
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             int c = 0;
--- a/test/jdk/com/sun/net/httpserver/bugs/B6373555.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6373555.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
  * @bug 6373555
  * @library /test/lib
  * @summary HTTP Server failing to answer client requests
+ * @run main B6373555
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6373555
  */
 
 import java.net.*;
@@ -105,7 +107,7 @@
                     .path("/test")
                     .toURLUnchecked();
                 System.out.println("URL: " + url);
-                HttpURLConnection con = (HttpURLConnection)url.openConnection();
+                HttpURLConnection con = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
                 con.setDoOutput(true);
                 con.setDoInput(true);
                 con.setRequestMethod("POST");
@@ -148,7 +150,8 @@
 
     private static HttpServer createHttpServer(ExecutorService execs)
         throws Exception {
-        InetSocketAddress inetAddress = new InetSocketAddress(0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress inetAddress = new InetSocketAddress(loopback, 0);
         HttpServer testServer = HttpServer.create(inetAddress, 15);
         testServer.setExecutor(execs);
         HttpContext context = testServer.createContext("/test");
--- a/test/jdk/com/sun/net/httpserver/bugs/B6393710.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6393710.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
  * @test
  * @bug 6393710
  * @summary  Non authenticated call followed by authenticated call never returns
+ * @run main B6393710
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6393710
  */
 
 import com.sun.net.httpserver.*;
@@ -65,7 +67,8 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ctx.setAuthenticator (new BasicAuthenticator ("test") {
@@ -76,7 +79,7 @@
 
         server.start ();
 
-        Socket s = new Socket ("localhost", server.getAddress().getPort());
+        Socket s = new Socket (loopback, server.getAddress().getPort());
         s.setSoTimeout (5000);
 
         OutputStream os = s.getOutputStream();
--- a/test/jdk/com/sun/net/httpserver/bugs/B6401598.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6401598.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,11 +26,14 @@
  * @library /test/lib
  * @bug 6401598
  * @summary  new HttpServer cannot serve binary stream data
+ * @run main B6401598
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6401598
  */
 
 import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
+import java.net.Proxy;
 import java.net.URL;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
@@ -84,7 +87,8 @@
 
         public static void main(String[] args) {
                 try {
-                        server = HttpServer.create(new InetSocketAddress(0), 400);
+                        InetAddress loopback = InetAddress.getLoopbackAddress();
+                        server = HttpServer.create(new InetSocketAddress(loopback, 0), 400);
                         server.createContext("/server/", new MyHandler());
                         exec = Executors.newFixedThreadPool(3);
                         server.setExecutor(exec);
@@ -123,11 +127,9 @@
                                 dis.close();
                         }
                         System.out.println ("Stopping");
-                        server.stop (1);
-                        exec.shutdown();
-                } catch (IOException e) {
-                        // TODO Auto-generated catch block
-                        e.printStackTrace();
+                } catch (Exception e) {
+                    throw new AssertionError("Unexpected exception: " + e, e);
+                } finally {
                         server.stop (1);
                         exec.shutdown();
                 }
@@ -137,7 +139,8 @@
 
         static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {
 
-                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
+                HttpURLConnection httpURLConnection =
+                    (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
 
                 httpURLConnection.setConnectTimeout(40000);
                 httpURLConnection.setReadTimeout(timeout);
--- a/test/jdk/com/sun/net/httpserver/bugs/B6431193.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6431193.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,13 +24,17 @@
 /**
  * @test
  * @bug 6431193
+ * @library /test/lib
  * @summary  The new HTTP server exits immediately
+ * @run main B6431193
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6431193
  */
 
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.*;
+import jdk.test.lib.net.URIBuilder;
 
 import com.sun.net.httpserver.*;
 
@@ -44,8 +48,8 @@
     }
 
     /**
-         * @param args
-         */
+     * @param args
+     */
     public static void main(String[] args) {
         class MyHandler implements HttpHandler {
             public void handle(HttpExchange t) throws IOException {
@@ -64,7 +68,8 @@
 
         HttpServer server;
         try {
-            server = HttpServer.create(new InetSocketAddress(0), 10);
+            InetAddress loopback = InetAddress.getLoopbackAddress();
+            server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);
 
             server.createContext("/apps", new MyHandler());
             server.setExecutor(null);
@@ -72,8 +77,13 @@
                 server.start();
             int port = server.getAddress().getPort();
             String s = "http://localhost:"+port+"/apps/foo";
-            URL url = new URL (s);
-            InputStream is = url.openStream();
+            URL url = URIBuilder.newBuilder()
+                      .scheme("http")
+                      .loopback()
+                      .port(port)
+                      .path("/apps/foo")
+                      .toURL();
+            InputStream is = url.openConnection(Proxy.NO_PROXY).getInputStream();
             read (is);
             server.stop (1);
             if (error) {
@@ -81,9 +91,8 @@
             }
 
         }
-        catch (IOException e) {
-            // TODO Auto-generated catch block
-                e.printStackTrace();
+        catch (Exception e) {
+            throw new AssertionError("Unexpected exception: " + e, e);
         }
     }
 }
--- a/test/jdk/com/sun/net/httpserver/bugs/B6433018.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6433018.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
  * @test
  * @bug 6433018
  * @summary  HTTP server sometimes sends bad request for browsers javascript
+ * @run main B6433018
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6433018
  */
 
 import com.sun.net.httpserver.*;
@@ -63,13 +65,14 @@
     public static void main(String[] args) throws Exception {
         CountDownLatch finished = new CountDownLatch(2);
         Handler handler = new Handler(finished);
-        InetSocketAddress addr = new InetSocketAddress(0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create(addr, 0);
         HttpContext ctx = server.createContext("/test", handler);
 
         server.start();
         int port = server.getAddress().getPort();
-        try (Socket s = new Socket("localhost", port);
+        try (Socket s = new Socket(loopback, port);
              OutputStream os = s.getOutputStream()) {
             os.write(cmd.getBytes());
             finished.await(30, TimeUnit.SECONDS);
--- a/test/jdk/com/sun/net/httpserver/bugs/B6526158.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6526158.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,9 @@
 /**
  * @test
  * @bug 6526158
+ * @library /test/lib
+ * @run main B6526158
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6526158
  * @summary  HttpExchange.getRequestBody().close() throws Exception
  */
 
@@ -36,6 +39,7 @@
 import java.security.*;
 import java.security.cert.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6526158 {
 
@@ -44,7 +48,8 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
 
@@ -52,8 +57,13 @@
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.setDoOutput (true);
         try {
             OutputStream os = new BufferedOutputStream (urlc.getOutputStream());
--- a/test/jdk/com/sun/net/httpserver/bugs/B6526913.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6526913.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,10 @@
 /**
  * @test
  * @bug 6526913
+ * @library /test/lib
  * @run main/othervm -Dhttp.keepAlive=false  B6526913
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dhttp.keepAlive=false B6526913
  * @summary  HttpExchange.getResponseBody().close() throws Exception
  */
 
@@ -37,12 +40,14 @@
 import java.security.*;
 import java.security.cert.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6526913 {
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
 
@@ -50,8 +55,13 @@
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection (Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             int c ,count = 0;
--- a/test/jdk/com/sun/net/httpserver/bugs/B6529200.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6529200.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
  * @test
  * @bug 6529200
  * @run main/othervm B6529200
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6529200
  * @summary  lightweight http server does not work with http1.0 clients
  */
 
@@ -42,7 +43,8 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
 
@@ -52,7 +54,7 @@
 
         /* test 1: keep-alive */
 
-        Socket sock = new Socket ("localhost", server.getAddress().getPort());
+        Socket sock = new Socket (loopback, server.getAddress().getPort());
         OutputStream os = sock.getOutputStream();
         System.out.println ("GET /test/foo HTTP/1.0\r\nConnection: keep-alive\r\n\r\n");
         os.write ("GET /test/foo HTTP/1.0\r\nConnection: keep-alive\r\n\r\n".getBytes());
--- a/test/jdk/com/sun/net/httpserver/bugs/B6744329.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6744329.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,9 @@
  * @test
  * @bug 6744329
  * @summary  Exception in light weight Http server
+ * @library /test/lib
+ * @run main B6744329
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6744329
  */
 
 import com.sun.net.httpserver.*;
@@ -36,20 +39,27 @@
 import java.security.*;
 import java.security.cert.*;
 import javax.net.ssl.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6744329 {
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             int c = 0;
@@ -59,6 +69,7 @@
             System.out.println ("OK");
         } catch (IOException e) {
             System.out.println ("exception");
+            e.printStackTrace();
             error = true;
         }
         server.stop(2);
--- a/test/jdk/com/sun/net/httpserver/bugs/B6886436.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B6886436.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,10 @@
 /**
  * @test
  * @bug 6886436
- * @summary
+ * @summary HttpServer should not send a body with 204 response.
+ * @library /test/lib
+ * @run main B6886436
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B6886436
  */
 
 import com.sun.net.httpserver.*;
@@ -34,6 +37,7 @@
 import java.util.logging.*;
 import java.io.*;
 import java.net.*;
+import jdk.test.lib.net.URIBuilder;
 
 public class B6886436 {
 
@@ -44,20 +48,26 @@
         logger.addHandler (c);
         logger.setLevel (Level.WARNING);
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress (loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         HttpContext ctx = server.createContext ("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
         server.setExecutor (executor);
         server.start ();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+            .scheme("http")
+            .loopback()
+            .port(server.getAddress().getPort())
+            .path("/test/foo.html")
+            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             while (is.read()!= -1) ;
             is.close ();
-            urlc = (HttpURLConnection)url.openConnection ();
+            urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
             urlc.setReadTimeout (3000);
             is = urlc.getInputStream();
             while (is.read()!= -1);
--- a/test/jdk/com/sun/net/httpserver/bugs/B8211420.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/B8211420.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,9 @@
 /**
  * @test
  * @bug 8211420
+ * @library /test/lib
  * @run main/othervm B8211420
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true B8211420
  * @summary
  */
 
@@ -36,45 +38,53 @@
 import java.io.*;
 import java.net.*;
 
+import jdk.test.lib.net.URIBuilder;
+
 public class B8211420 {
 
-    public static void main (String[] args) throws Exception {
-        Logger logger = Logger.getLogger ("com.sun.net.httpserver");
+    public static void main(String[] args) throws Exception {
+        Logger logger = Logger.getLogger("com.sun.net.httpserver");
         ConsoleHandler c = new ConsoleHandler();
-        c.setLevel (Level.WARNING);
-        logger.addHandler (c);
-        logger.setLevel (Level.WARNING);
+        c.setLevel(Level.WARNING);
+        logger.addHandler(c);
+        logger.setLevel(Level.WARNING);
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
-        HttpServer server = HttpServer.create (addr, 0);
-        HttpContext ctx = server.createContext ("/test", handler);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
+        HttpServer server = HttpServer.create(addr, 0);
+        HttpContext ctx = server.createContext("/test", handler);
         ExecutorService executor = Executors.newCachedThreadPool();
-        server.setExecutor (executor);
-        server.start ();
+        server.setExecutor(executor);
+        server.start();
 
-        URL url = new URL ("http://localhost:"+server.getAddress().getPort()+"/test/foo.html");
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+        URL url = URIBuilder.newBuilder()
+                            .scheme("http")
+                            .host(server.getAddress().getAddress())
+                            .port(server.getAddress().getPort())
+                            .path("/test/foo.html")
+                            .toURL();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         try {
             InputStream is = urlc.getInputStream();
             while (is.read()!= -1) ;
             is.close ();
             String prop = urlc.getHeaderField("Content-length");
-                System.out.println ("Content-length = " + prop + " should be null");
+                System.out.println("Content-length = " + prop + " should be null");
             if (prop != null)
                 throw new RuntimeException("Content-length was present");
 
-            urlc = (HttpURLConnection)url.openConnection();
+            urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
             is = urlc.getInputStream();
             while (is.read()!= -1) ;
-            is.close ();
+            is.close();
             if (urlc.getResponseCode() != 304) // expected for 2nd test
                 throw new RuntimeException("wrong response code");
             String clen = urlc.getHeaderField("Content-length");
-            System.out.println ("Content-length = " + clen + " should be 99");
-            System.out.println ("len = " + clen.length());
+            System.out.println("Content-length = " + clen + " should be 99");
+            System.out.println("len = " + clen.length());
             if (clen == null || !clen.equals("99"))
                 throw new RuntimeException("Content-length not present or has wrong value");
-            System.out.println ("OK");
+            System.out.println("OK");
         } finally {
             server.stop(2);
             executor.shutdown();
@@ -91,7 +101,7 @@
             InputStream is = t.getRequestBody();
             Headers map = t.getRequestHeaders();
             Headers rmap = t.getResponseHeaders();
-            while (is.read () != -1) ;
+            while (is.read() != -1) ;
             is.close();
             if (invocation++ == 1) {
                 // send a 204 response with no body
--- a/test/jdk/com/sun/net/httpserver/bugs/FixedLengthInputStream.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/FixedLengthInputStream.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,20 +25,26 @@
  * @test
  * @bug 6756771 6755625
  * @summary  com.sun.net.httpserver.HttpServer should handle POSTs larger than 2Gig
+ * @library /test/lib
+ * @run main FixedLengthInputStream
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true FixedLengthInputStream
  */
 
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintStream;
+import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.HttpURLConnection;
+import java.net.Proxy;
 import java.net.URL;
 import java.net.Socket;
 import java.util.logging.*;
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 import com.sun.net.httpserver.HttpServer;
+import jdk.test.lib.net.URIBuilder;
 
 public class FixedLengthInputStream
 {
@@ -48,8 +54,13 @@
         HttpServer httpServer = startHttpServer();
         int port = httpServer.getAddress().getPort();
         try {
-            URL url = new URL("http://localhost:" + port + "/flis/");
-            HttpURLConnection uc = (HttpURLConnection)url.openConnection();
+            URL url = URIBuilder.newBuilder()
+                .scheme("http")
+                .loopback()
+                .port(port)
+                .path("/flis/")
+                .toURLUnchecked();
+            HttpURLConnection uc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
             uc.setDoOutput(true);
             uc.setRequestMethod("POST");
             uc.setFixedLengthStreamingMode(POST_SIZE);
@@ -90,7 +101,8 @@
             logger.setLevel(Level.FINEST);
             logger.addHandler(outHandler);
         }
-        HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        HttpServer httpServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
         httpServer.createContext("/flis/", new MyHandler(POST_SIZE));
         httpServer.start();
         return httpServer;
--- a/test/jdk/com/sun/net/httpserver/bugs/HeadTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/HeadTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,11 +24,16 @@
 /**
  * @test
  * @bug 6886723
+ * @library /test/lib
+ * @run main HeadTest
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true HeadTest
  * @summary light weight http server doesn't return correct status code for HEAD requests
  */
 
+import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.HttpURLConnection;
+import java.net.Proxy;
 import java.net.URL;
 import java.io.IOException;
 import java.util.concurrent.ExecutorService;
@@ -37,6 +42,7 @@
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 import com.sun.net.httpserver.HttpServer;
+import jdk.test.lib.net.URIBuilder;
 
 public class HeadTest {
 
@@ -45,7 +51,8 @@
     }
 
     static void server() throws Exception {
-        InetSocketAddress inetAddress = new InetSocketAddress(0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress inetAddress = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create(inetAddress, 5);
         try {
             server.setExecutor(Executors.newFixedThreadPool(5));
@@ -88,7 +95,13 @@
                 }
             });
             server.start();
-            String urlStr = "http://localhost:" + server.getAddress().getPort() + "/";
+            String urlStr = URIBuilder.newBuilder()
+                .scheme("http")
+                .loopback()
+                .port(server.getAddress().getPort())
+                .path("/")
+                .build()
+                .toString();
             System.out.println("Server is at " + urlStr);
 
             // Run the chunked client
@@ -107,7 +120,7 @@
     }
 
     static void runClient(String urlStr) throws Exception {
-        HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
+        HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(Proxy.NO_PROXY);
         conn.setRequestMethod("HEAD");
         int status = conn.getResponseCode();
         if (status != 200) {
--- a/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java	Wed Jun 12 10:02:49 2019 +0530
@@ -90,7 +90,8 @@
         logger.setLevel(Level.ALL);
         logger.addHandler(h);
 
-        InetSocketAddress addr = new InetSocketAddress(0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create(addr, 10);
         HttpContext ct = server.createContext("/", new Handler());
         ExecutorService ex = Executors.newCachedThreadPool();
@@ -101,7 +102,7 @@
 
         // Test 1: fixed length
 
-        Socket sock = new Socket(InetAddress.getLoopbackAddress(), port);
+        Socket sock = new Socket(loopback, port);
         String s1 = "POST /foo HTTP/1.1\r\nContent-length: 200000\r\n"
                 + "\r\nfoo bar99";
 
@@ -115,7 +116,7 @@
 
         String s2 = "POST /foo HTTP/1.1\r\nTransfer-encoding: chunked\r\n\r\n" +
                 "100\r\nFoo bar";
-        sock = new Socket(InetAddress.getLoopbackAddress(), port);
+        sock = new Socket(loopback, port);
         os = sock.getOutputStream();
         os.write(s2.getBytes(StandardCharsets.ISO_8859_1));
         Thread.sleep(500);
--- a/test/jdk/java/net/ResponseCache/Test2.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/java/net/ResponseCache/Test2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
  * @summary Check for CRL results in IllegalArgumentException "white space not allowed"
  * @modules jdk.httpserver
  * @run main/othervm Test2
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true Test2
  */
 
 import com.sun.net.httpserver.*;
@@ -69,11 +70,12 @@
 
     public static void main (String[] args) throws Exception {
         Handler handler = new Handler();
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetAddress loopback = InetAddress.getLoopbackAddress();
+        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
         HttpServer server = HttpServer.create (addr, 0);
         port = server.getAddress().getPort();
         HttpContext ctx = server.createContext ("/test", handler);
-        System.out.println ("Server: " + server.getAddress().getPort());
+        System.out.println ("Server: " + server.getAddress());
         ResponseCache.setDefault(new Cache());
 
         ExecutorService executor = Executors.newCachedThreadPool();
@@ -95,7 +97,7 @@
             .toURLUnchecked();
         System.out.println("Redir URL: " + redir);
 
-        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
         urlc.addRequestProperty("X-Foo", "bar");
         urlc.setInstanceFollowRedirects(true);
         System.out.println(urlc.getResponseCode());
--- a/test/jdk/java/net/URL/GetContent.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/java/net/URL/GetContent.java	Wed Jun 12 10:02:49 2019 +0530
@@ -26,6 +26,8 @@
  * @bug 4145315
  * @library /test/lib
  * @summary Test a read from nonexistant URL
+ * @run main GetContent
+ * @run main/othervm -Djava.net.preferIPv6Addresses GetContent
  */
 
 import java.net.*;
@@ -37,8 +39,7 @@
      ServerSocket ss;
 
      public void run() {
-        try {
-            Socket s = ss.accept();
+        try (Socket s = ss.accept()) {
             s.setTcpNoDelay(true);
 
             PrintStream out = new PrintStream(
@@ -57,7 +58,6 @@
             // client get error and re-establish connection
             Thread.sleep(2000);
 
-            s.close();
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
@@ -66,8 +66,10 @@
      }
 
      GetContent() throws Exception {
+         InetAddress loopback = InetAddress.getLoopbackAddress();
+         ss = new ServerSocket();
+         ss.bind(new InetSocketAddress(loopback, 0));
 
-         ss = new ServerSocket(0);
          Thread thr = new Thread(this);
          thr.start();
 
@@ -79,7 +81,8 @@
                  .port(ss.getLocalPort())
                  .path("/no-such-name")
                  .toURL();
-             Object obj = url.getContent();
+             Object obj = url.openConnection(Proxy.NO_PROXY)
+                          .getContent();
              InputStream in = (InputStream) obj;
              byte buff[] = new byte[200];
              int len = in.read(buff);
--- a/test/jdk/java/rmi/activation/CommandEnvironment/SetChildEnv.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/java/rmi/activation/CommandEnvironment/SetChildEnv.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -123,9 +123,7 @@
                     "WHO INQUIRE ABOUT MY PARENTS.";
 
             System.out.println(complaint);
-            //Runtime.getRuntime().traceMethodCalls(true);
             String res = doctor.complain(complaint);
-            //Runtime.getRuntime().traceMethodCalls(false);
             System.out.println (" => " + res);
 
             // Get debugExec line, allowing 15 seconds for it to flush
--- a/test/jdk/javax/net/ssl/DTLS/PacketLossRetransmission.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/javax/net/ssl/DTLS/PacketLossRetransmission.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2019 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@
  * @run main/othervm PacketLossRetransmission client 1 client_hello
  * @run main/othervm PacketLossRetransmission client 2 server_hello
  * @run main/othervm PacketLossRetransmission client 3 hello_verify_request
- * @run main/othervm PacketLossRetransmission client 4 new_session_ticket
+ * @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false PacketLossRetransmission client 4 new_session_ticket
  * @run main/othervm PacketLossRetransmission client 11 certificate
  * @run main/othervm PacketLossRetransmission client 12 server_key_exchange
  * @run main/othervm PacketLossRetransmission client 13 certificate_request
@@ -51,7 +51,7 @@
  * @run main/othervm PacketLossRetransmission server 1 client_hello
  * @run main/othervm PacketLossRetransmission server 2 server_hello
  * @run main/othervm PacketLossRetransmission server 3 hello_verify_request
- * @run main/othervm PacketLossRetransmission server 4 new_session_ticket
+ * @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false PacketLossRetransmission server 4 new_session_ticket
  * @run main/othervm PacketLossRetransmission server 11 certificate
  * @run main/othervm PacketLossRetransmission server 12 server_key_exchange
  * @run main/othervm PacketLossRetransmission server 13 certificate_request
--- a/test/jdk/javax/net/ssl/SSLSession/SSLCtxAccessToSessCtx.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/javax/net/ssl/SSLSession/SSLCtxAccessToSessCtx.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,9 @@
  * @test
  * @bug 4473210
  * @summary SSLSessionContext should be accessible from SSLContext
- * @run main/othervm SSLCtxAccessToSessCtx
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false
+ *   SSLCtxAccessToSessCtx
+ *
  *
  *     SunJSSE does not support dynamic system properties, no way to re-use
  *     system properties in samevm/agentvm mode.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jdk/jfr/startupargs/TestStartNoSettings.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.jfr.startupargs;
+
+import jdk.jfr.Event;
+import jdk.jfr.EventType;
+import jdk.jfr.FlightRecorder;
+import jdk.jfr.Name;
+import jdk.jfr.Recording;
+
+/**
+ * @test
+ * @summary Start a FlightRecording without any settings (not even default).
+ * @key jfr
+ * @requires vm.hasJFR
+ * @library /test/lib
+ * @run main/othervm jdk.jfr.startupargs.TestStartNoSettings
+ *      -XX:StartFlightRecording=settings=none
+ */
+public class TestStartNoSettings {
+
+    @Name("UserEvent")
+    static class UserEvent extends Event {
+    }
+
+    public static void main(String[] a) throws Exception {
+        boolean userEnabled = false;
+        try (Recording r = new Recording()) {
+            r.start();
+            UserEvent e = new UserEvent();
+            e.commit();
+            for (EventType et : FlightRecorder.getFlightRecorder().getEventTypes()) {
+                if (et.isEnabled()) {
+                    if (!et.getName().equals("UserEvent")) {
+                        throw new Exception("Only 'UserEvent' should be enabled");
+                    }
+                    userEnabled = true;
+                }
+            }
+        }
+
+        if (!userEnabled)  {
+            throw new Exception("Expected 'UserEvent' to be enabled with -XX:StartFlightRecording=settings=none");
+        }
+    }
+}
--- a/test/jdk/sun/net/www/http/HttpClient/StreamingRetry.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/net/www/http/HttpClient/StreamingRetry.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,15 @@
  * @test
  * @bug 6672144 8050983
  * @summary Do not retry failed request with a streaming body.
+ * @library /test/lib
+ * @run main StreamingRetry
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true StreamingRetry
  */
 
 import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
 import java.net.ServerSocket;
 import java.net.URL;
 import java.io.IOException;
@@ -35,6 +41,8 @@
 import java.io.OutputStream;
 import static java.lang.System.out;
 
+import jdk.test.lib.net.URIBuilder;
+
 public class StreamingRetry implements Runnable {
     static final int ACCEPT_TIMEOUT = 20 * 1000; // 20 seconds
     volatile ServerSocket ss;
@@ -55,7 +63,8 @@
     }
 
     void test(String method) throws Exception {
-        ss = new ServerSocket(0);
+        ss = new ServerSocket();
+        ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
         ss.setSoTimeout(ACCEPT_TIMEOUT);
         int port = ss.getLocalPort();
 
@@ -63,8 +72,13 @@
         otherThread.start();
 
         try {
-            URL url = new URL("http://localhost:" + port + "/");
-            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
+            URL url = URIBuilder.newBuilder()
+                      .scheme("http")
+                      .host(ss.getInetAddress())
+                      .port(port)
+                      .path("/")
+                      .toURL();
+            HttpURLConnection uc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
             uc.setDoOutput(true);
             if (method != null)
                 uc.setRequestMethod(method);
--- a/test/jdk/sun/net/www/protocol/http/DigestTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/net/www/protocol/http/DigestTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,13 @@
  * @bug 4432213
  * @modules java.base/sun.net.www
  * @run main/othervm -Dhttp.auth.digest.validateServer=true DigestTest
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dhttp.auth.digest.validateServer=true DigestTest
+ * @run main/othervm -Dhttp.auth.digest.validateServer=true
+                     -Dtest.succeed=true DigestTest
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true
+ *                   -Dhttp.auth.digest.validateServer=true
+                     -Dtest.succeed=true DigestTest
  * @summary  Need to support Digest Authentication for Proxies
  */
 
@@ -57,13 +64,15 @@
         "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
         "Server: Apache/1.3.14 (Unix)\r\n" +
         "Content-Type: text/html; charset=iso-8859-1\r\n" +
-        "Transfer-encoding: chunked\r\n\r\n"+
+        "Transfer-encoding: chunked\r\n";
+    String body =
         "B\r\nHelloWorld1\r\n"+
         "B\r\nHelloWorld2\r\n"+
         "B\r\nHelloWorld3\r\n"+
         "B\r\nHelloWorld4\r\n"+
         "B\r\nHelloWorld5\r\n"+
-        "0\r\n"+
+        "0\r\n\r\n";
+    String authInfo =
         "Authentication-Info: ";
 
     DigestServer (ServerSocket y) {
@@ -84,7 +93,7 @@
                 s1 = s.accept ();
                 is = s1.getInputStream ();
                 os = s1.getOutputStream ();
-                is.read ();
+                //is.read ();
                 // need to get the cnonce out of the response
                 MessageHeader header = new MessageHeader (is);
                 String raw = header.findValue ("Authorization");
@@ -92,7 +101,7 @@
                 String cnonce = parser.findValue ("cnonce");
                 String cnstring = parser.findValue ("nc");
 
-                String reply = reply2 + getAuthorization (uri, "GET", cnonce, cnstring) +"\r\n";
+                String reply = reply2 + authInfo + getAuthorization (uri, "GET", cnonce, cnstring) +"\r\n" + body;
                 os.write (reply.getBytes());
                 Thread.sleep (2000);
                 s1.close ();
@@ -193,6 +202,9 @@
 
 public class DigestTest {
 
+    static final boolean SUCCEED =
+        Boolean.parseBoolean(System.getProperty("test.succeed", "false"));
+
     static class MyAuthenticator extends Authenticator {
         public MyAuthenticator () {
             super ();
@@ -200,7 +212,9 @@
 
         public PasswordAuthentication getPasswordAuthentication ()
         {
-            return (new PasswordAuthentication ("user", "Wrongpassword".toCharArray()));
+            char[] passwd = SUCCEED ? DigestServer.passwd.clone()
+                                      : "Wrongpassword".toCharArray();
+            return new PasswordAuthentication("user", passwd);
         }
     }
 
@@ -210,34 +224,47 @@
         DigestServer server;
         ServerSocket sock;
 
+        InetAddress loopback = InetAddress.getLoopbackAddress();
         try {
-            sock = new ServerSocket (0);
-            port = sock.getLocalPort ();
+            sock = new ServerSocket();
+            sock.bind(new InetSocketAddress(loopback, 0));
+            port = sock.getLocalPort();
         }
         catch (Exception e) {
             System.out.println ("Exception: " + e);
-            return;
+            throw e;
         }
 
         server = new DigestServer(sock);
         server.start ();
         boolean passed = false;
+        ProtocolException exception = null;
 
         try  {
             Authenticator.setDefault (new MyAuthenticator ());
-            String s = "http://localhost:" + port + DigestServer.uri;
+            String address = loopback.getHostAddress();
+            if (address.indexOf(':') > -1)  address = "[" + address + "]";
+            String s = "http://" + address + ":" + port + DigestServer.uri;
             URL url = new URL(s);
-            java.net.URLConnection conURL =  url.openConnection();
+            java.net.URLConnection conURL =  url.openConnection(Proxy.NO_PROXY);
 
             InputStream in = conURL.getInputStream();
             while (in.read () != -1) {}
             in.close ();
+            if (SUCCEED) passed = true;
         } catch(ProtocolException e) {
-            passed = true;
+            exception = e;
+            if (!SUCCEED) passed = true;
         }
 
         if (!passed) {
-            throw new RuntimeException ("Expected a ProtocolException from wrong password");
+            if (!SUCCEED) {
+                throw new RuntimeException("Expected a ProtocolException from wrong password");
+            } else {
+                assert exception != null;
+                throw new RuntimeException("Unexpected ProtocolException from correct password: "
+                                            + exception, exception);
+            }
         }
     }
 }
--- a/test/jdk/sun/net/www/protocol/http/RelativeRedirect.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/net/www/protocol/http/RelativeRedirect.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
  * @library ../../httptest/
  * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main RelativeRedirect
+ * @run main/othervm -Djava.net.preferIPv6Addresses=true RelativeRedirect
  * @summary URLConnection cannot handle redirects
  */
 
@@ -58,7 +59,7 @@
 
     void secondReply (HttpTransaction req) throws IOException {
         if (req.getRequestURI().toString().equals("/redirect/file.html") &&
-            req.getRequestHeader("Host").equals("localhost:"+server.getLocalPort())) {
+            req.getRequestHeader("Host").equals(authority(server.getLocalPort()))) {
             req.setResponseEntityBody ("Hello .");
             req.sendResponse (200, "Ok");
         } else {
@@ -86,15 +87,25 @@
         }
     }
 
+   static String authority(int port) {
+       InetAddress loopback = InetAddress.getLoopbackAddress();
+       String hostaddr = loopback.getHostAddress();
+       if (hostaddr.indexOf(':') > -1) {
+           hostaddr = "[" + hostaddr + "]";
+       }
+       return hostaddr + ":" + port;
+   }
+
     public static void main (String[] args) throws Exception {
+        InetAddress loopback = InetAddress.getLoopbackAddress();
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new TestHttpServer (new RelativeRedirect(), 1, 10, 0);
+            server = new TestHttpServer (new RelativeRedirect(), 1, 10, loopback, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
-            URL url = new URL("http://localhost:"+server.getLocalPort());
+            URL url = new URL("http://" + authority(server.getLocalPort()));
             System.out.println ("client opening connection to: " + url);
-            HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
+            HttpURLConnection urlc = (HttpURLConnection)url.openConnection (Proxy.NO_PROXY);
             InputStream is = urlc.getInputStream ();
             is.close();
         } catch (Exception e) {
--- a/test/jdk/sun/rmi/log/ReliableLog/Recovery.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/rmi/log/ReliableLog/Recovery.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,13 +88,7 @@
 
                     Recovery handler = new Recovery();
                     ReliableLog log;
-                    if (size == 4 && deathpoint == 6) {
-                        Runtime.getRuntime().traceMethodCalls(true);
-                    }
                     log = new ReliableLog(dir, handler);
-                    if (size == 4 && deathpoint == 6) {
-                        Runtime.getRuntime().traceMethodCalls(false);
-                    }
 
                     // Generate a number of updates (size - 1) until failing
                     int i;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Cipher/Test4512704.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main Test4512704
+ * @summary Verify that AES cipher can generate default IV in encrypt mode
+ */
+import java.io.PrintStream;
+import java.security.*;
+import java.security.spec.*;
+import java.util.Random;
+
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.security.Provider;
+
+public class Test4512704 extends PKCS11Test {
+
+    public void test(String mode, Provider p) throws Exception {
+        Cipher c;
+        String transformation = "AES/" + mode + "/NoPadding";
+
+        try {
+            transformation = "AES/" + mode + "/NoPadding";
+            c = Cipher.getInstance(transformation, p);
+        } catch (GeneralSecurityException e) {
+            System.out.println("Skip testing " + p.getName() +
+                    ", no support for " + mode);
+            return;
+        }
+        SecretKey key = new SecretKeySpec(new byte[16], "AES");
+
+        AlgorithmParameterSpec aps = null;
+        Cipher ci = Cipher.getInstance(transformation, p);
+        try {
+            ci.init(Cipher.ENCRYPT_MODE, key, aps);
+        } catch(InvalidAlgorithmParameterException ex) {
+            throw new Exception("parameter should be generated when null is specified!");
+        }
+        System.out.println(transformation + ": Passed");
+    }
+
+    public static void main (String[] args) throws Exception {
+        main(new Test4512704(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        test("GCM", p);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCM.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main TestCICOWithGCM
+ * @summary Test CipherInputStream/OutputStream with AES GCM mode.
+ * @key randomness
+ */
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+import java.io.*;
+
+import java.util.*;
+
+public class TestCICOWithGCM extends PKCS11Test {
+    public static void main(String[] args) throws Exception {
+        main(new TestCICOWithGCM(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        test("GCM", p);
+    }
+
+    public void test(String mode, Provider p) throws Exception {
+        Cipher c;
+        try {
+            String transformation = "AES/" + mode + "/NoPadding";
+            c = Cipher.getInstance(transformation, p);
+        } catch (GeneralSecurityException e) {
+            System.out.println("Skip testing " + p.getName() +
+                    ", no support for " + mode);
+            return;
+        }
+
+        SecretKey key = new SecretKeySpec(new byte[16], "AES");
+
+        //do initialization of the plainText
+        byte[] plainText = new byte[800];
+        Random rdm = new Random();
+        rdm.nextBytes(plainText);
+
+        //init ciphers
+        Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
+        encCipher.init(Cipher.ENCRYPT_MODE, key);
+        Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
+        decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters());
+
+        //init cipher streams
+        ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
+        CipherInputStream ciInput = new CipherInputStream(baInput, encCipher);
+        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
+        CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher);
+
+        //do test
+        byte[] buffer = new byte[800];
+        int len = ciInput.read(buffer);
+        System.out.println("read " + len + " bytes from input buffer");
+
+        while (len != -1) {
+            ciOutput.write(buffer, 0, len);
+            System.out.println("wite " + len + " bytes to output buffer");
+            len = ciInput.read(buffer);
+            if (len != -1) {
+                System.out.println("read " + len + " bytes from input buffer");
+            } else {
+                System.out.println("finished reading");
+            }
+        }
+
+        ciOutput.flush();
+        ciInput.close();
+        ciOutput.close();
+        byte[] recovered = baOutput.toByteArray();
+        System.out.println("recovered " + recovered.length + " bytes");
+        if (!Arrays.equals(plainText, recovered)) {
+            throw new RuntimeException("diff check failed!");
+        } else {
+            System.out.println("diff check passed");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCMAndAAD.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main TestCICOWithGCMAndAAD
+ * @summary Test CipherInputStream/OutputStream with AES GCM mode with AAD.
+ * @key randomness
+ */
+import java.io.*;
+import java.security.*;
+import java.util.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+
+public class TestCICOWithGCMAndAAD extends PKCS11Test {
+    public static void main(String[] args) throws Exception {
+        main(new TestCICOWithGCMAndAAD(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        test("GCM", p);
+//        test("CCM", p);
+    }
+
+    public void test(String mode, Provider p) throws Exception {
+        Cipher c;
+        try {
+            String transformation = "AES/" + mode + "/NoPadding";
+            c = Cipher.getInstance(transformation, p);
+        } catch (GeneralSecurityException e) {
+            System.out.println("Skip testing " + p.getName() +
+                    ", no support for " + mode);
+            return;
+        }
+        SecretKey key = new SecretKeySpec(new byte[16], "AES");
+
+        //Do initialization of the plainText
+        byte[] plainText = new byte[700];
+        Random rdm = new Random();
+        rdm.nextBytes(plainText);
+
+        byte[] aad = new byte[128];
+        rdm.nextBytes(aad);
+        byte[] aad2 = aad.clone();
+        aad2[50]++;
+
+        Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
+        encCipher.init(Cipher.ENCRYPT_MODE, key);
+        encCipher.updateAAD(aad);
+        Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
+        decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters());
+        decCipher.updateAAD(aad);
+
+        byte[] recovered = test(encCipher, decCipher, plainText);
+        if (!Arrays.equals(plainText, recovered)) {
+            throw new Exception("sameAAD: diff check failed!");
+        } else System.out.println("sameAAD: passed");
+
+        encCipher.init(Cipher.ENCRYPT_MODE, key);
+        encCipher.updateAAD(aad2);
+        recovered = test(encCipher, decCipher, plainText);
+        if (recovered != null && recovered.length != 0) {
+            throw new Exception("diffAAD: no data should be returned!");
+        } else System.out.println("diffAAD: passed");
+   }
+
+   private static byte[] test(Cipher encCipher, Cipher decCipher, byte[] plainText)
+            throws Exception {
+        //init cipher streams
+        ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
+        CipherInputStream ciInput = new CipherInputStream(baInput, encCipher);
+        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
+        CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher);
+
+        //do test
+        byte[] buffer = new byte[200];
+        int len = ciInput.read(buffer);
+        System.out.println("read " + len + " bytes from input buffer");
+
+        while (len != -1) {
+            ciOutput.write(buffer, 0, len);
+            System.out.println("wite " + len + " bytes to output buffer");
+            len = ciInput.read(buffer);
+            if (len != -1) {
+                System.out.println("read " + len + " bytes from input buffer");
+            } else {
+                System.out.println("finished reading");
+            }
+        }
+
+        ciOutput.flush();
+        ciInput.close();
+        ciOutput.close();
+
+        return baOutput.toByteArray();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Cipher/TestGCMKeyAndIvCheck.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main TestGCMKeyAndIvCheck
+ * @summary Ensure that same key+iv can't be repeated used for encryption.
+ */
+
+
+import java.security.*;
+import java.security.spec.AlgorithmParameterSpec;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+
+import java.util.*;
+
+public class TestGCMKeyAndIvCheck extends PKCS11Test {
+
+    private static final byte[] AAD = new byte[5];
+    private static final byte[] PT = new byte[18];
+
+    public static void main(String[] args) throws Exception {
+        main(new TestGCMKeyAndIvCheck(), args);
+    }
+
+    private static void checkISE(Cipher c) throws Exception {
+        // Subsequent encryptions should fail
+        try {
+            c.updateAAD(AAD);
+            throw new Exception("Should throw ISE for updateAAD()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+
+        try {
+            c.update(PT);
+            throw new Exception("Should throw ISE for update()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+        try {
+            c.doFinal(PT);
+            throw new Exception("Should throw ISE for doFinal()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+    }
+
+    public void test(String mode, Provider p) throws Exception {
+        Cipher c;
+        try {
+            String transformation = "AES/" + mode + "/NoPadding";
+            c = Cipher.getInstance(transformation, p);
+        } catch (GeneralSecurityException e) {
+            System.out.println("Skip testing " + p.getName() +
+                    ", no support for " + mode);
+            return;
+        }
+        SecretKey key = new SecretKeySpec(new byte[16], "AES");
+        // First try parameter-less init.
+        c.init(Cipher.ENCRYPT_MODE, key);
+        c.updateAAD(AAD);
+        byte[] ctPlusTag = c.doFinal(PT);
+
+        // subsequent encryption should fail unless re-init w/ different key+iv
+        checkISE(c);
+
+        // Validate the retrieved parameters against the IV and tag length.
+        AlgorithmParameters params = c.getParameters();
+        if (params == null) {
+            throw new Exception("getParameters() should not return null");
+        }
+        byte[] iv = null;
+        int tagLength = 0; // in bits
+        if (mode.equalsIgnoreCase("GCM")) {
+            GCMParameterSpec spec = params.getParameterSpec(GCMParameterSpec.class);
+            tagLength = spec.getTLen();
+            iv = spec.getIV();
+        } else {
+            throw new RuntimeException("Error: Unsupported mode: " + mode);
+        }
+        if (tagLength != (ctPlusTag.length - PT.length)*8) {
+            throw new Exception("Parameters contains incorrect TLen value");
+        }
+        if (!Arrays.equals(iv, c.getIV())) {
+            throw new Exception("Parameters contains incorrect IV value");
+        }
+
+        // Should be ok to use the same key+iv for decryption
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        byte[] recovered = c.doFinal(ctPlusTag);
+        if (!Arrays.equals(recovered, PT)) {
+            throw new Exception("decryption result mismatch");
+        }
+
+        // Now try to encrypt again using the same key+iv; should fail also
+        try {
+            c.init(Cipher.ENCRYPT_MODE, key, params);
+            throw new Exception("Should throw exception when same key+iv is used");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+
+        // Now try to encrypt again using parameter-less init; should work
+        c.init(Cipher.ENCRYPT_MODE, key);
+        c.doFinal(PT);
+
+        // make sure a different iv is used
+        byte[] ivNew = c.getIV();
+        if (Arrays.equals(iv, ivNew)) {
+            throw new Exception("IV should be different now");
+        }
+
+        // Now try to encrypt again using a different parameter; should work
+        AlgorithmParameterSpec spec2 = new GCMParameterSpec(128, new byte[30]);
+        c.init(Cipher.ENCRYPT_MODE, key, spec2);
+        c.updateAAD(AAD);
+        c.doFinal(PT);
+        // subsequent encryption should fail unless re-init w/ different key+iv
+        checkISE(c);
+
+        // Now try decryption twice in a row; no re-init required and
+        // same parameters is used.
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+        if (!Arrays.equals(recovered, PT)) {
+            throw new Exception("decryption result mismatch");
+        }
+
+        // Now try decryption again and re-init using the same parameters
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+
+        // init to decrypt w/o parameters; should fail with IKE as
+        // javadoc specified
+        try {
+            c.init(Cipher.DECRYPT_MODE, key);
+            throw new Exception("Should throw IKE for dec w/o params");
+        } catch (InvalidKeyException ike) {
+            // expected
+        }
+
+        // Lastly, try encryption AND decryption w/ wrong type of parameters,
+        // e.g. IvParameterSpec
+        try {
+            c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
+            throw new Exception("Should throw IAPE");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+        try {
+            c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
+            throw new Exception("Should throw IAPE");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+
+        System.out.println("Test Passed!");
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        test("GCM", p);
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Cipher/TestKATForGCM.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,322 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main TestKATForGCM
+ * @summary Known Answer Test for AES cipher with GCM mode support in
+ * PKCS11 provider.
+ */
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+
+import java.util.*;
+
+public class TestKATForGCM extends PKCS11Test {
+
+    // Utility methods
+    private static byte[] HexToBytes(String hexVal) {
+        if (hexVal == null) return new byte[0];
+        byte[] result = new byte[hexVal.length()/2];
+        for (int i = 0; i < result.length; i++) {
+            // 2 characters at a time
+            String byteVal = hexVal.substring(2*i, 2*i +2);
+            result[i] = Integer.valueOf(byteVal, 16).byteValue();
+        }
+        return result;
+    }
+
+    private static class TestVector {
+        SecretKey key;
+        byte[] plainText;
+        byte[] aad;
+        byte[] cipherText;
+        byte[] tag;
+        GCMParameterSpec spec;
+        String info;
+
+        TestVector(String key, String iv, String pt, String aad,
+                   String ct, String tag) {
+            this.key = new SecretKeySpec(HexToBytes(key), "AES");
+            this.plainText = HexToBytes(pt);
+            this.aad = HexToBytes(aad);
+            this.cipherText = HexToBytes(ct);
+            this.tag = HexToBytes(tag);
+            this.spec = new GCMParameterSpec(this.tag.length * 8, HexToBytes(iv));
+            this.info = "key=" + key + ", iv=" + iv + ", pt=" + pt +
+                ",aad=" + aad + ", ct=" + ct + ", tag=" + tag;
+        }
+
+        public String toString() {
+            return info;
+        }
+    }
+
+    // These test vectors are found off NIST's CAVP page
+    // http://csrc.nist.gov/groups/STM/cavp/index.html
+    // inside the link named "GCM Test Vectors", i.e.
+    // http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
+    // CAVS 14.0, set of test vectors w/ count = 0, keysize = 128
+    private static TestVector[] testValues = {
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, no aad
+        new TestVector("11754cd72aec309bf52f7687212e8957",
+                       "3c819d9a9bed087615030b65",
+                       null, null, null,
+                       "250327c674aaf477aef2675748cf6971"),
+        new TestVector("272f16edb81a7abbea887357a58c1917",
+                       "794ec588176c703d3d2a7a07",
+                       null, null, null,
+                       "b6e6f197168f5049aeda32dafbdaeb"),
+        new TestVector("81b6844aab6a568c4556a2eb7eae752f",
+                       "ce600f59618315a6829bef4d",
+                       null, null, null,
+                       "89b43e9dbc1b4f597dbbc7655bb5"),
+        new TestVector("cde2f9a9b1a004165ef9dc981f18651b",
+                       "29512c29566c7322e1e33e8e",
+                       null, null, null,
+                       "2e58ce7dabd107c82759c66a75"),
+        new TestVector("b01e45cc3088aaba9fa43d81d481823f",
+                       "5a2c4a66468713456a4bd5e1",
+                       null, null, null,
+                       "014280f944f53c681164b2ff"),
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, 16-byte aad
+        new TestVector("77be63708971c4e240d1cb79e8d77feb",
+                       "e0e00f19fed7ba0136a797f3",
+                       null,
+                       "7a43ec1d9c0a5a78a0b16533a6213cab",
+                       null,
+                       "209fcc8d3675ed938e9c7166709dd946"),
+        new TestVector("da0b615656135194ba6d3c851099bc48",
+                       "d39d4b4d3cc927885090e6c3",
+                       null,
+                       "e7e5e6f8dac913036cb2ff29e8625e0e",
+                       null,
+                       "ab967711a5770461724460b07237e2"),
+        new TestVector("7e0986937a88eef894235aba4a2f43b2",
+                       "92c4a631695907166b422d60",
+                       null,
+                       "85c185f8518f9f2cd597a8f9208fc76b",
+                       null,
+                       "3bb916b728df94fe9d1916736be1"),
+        new TestVector("c3db570d7f0c21e86b028f11465d1dc9",
+                       "f86970f58ceef89fc7cb679e",
+                       null,
+                       "c095240708c0f57c288d86090ae34ee1",
+                       null,
+                       "e043c52160d652e82c7262fcf4"),
+        new TestVector("bea48ae4980d27f357611014d4486625",
+                       "32bddb5c3aa998a08556454c",
+                       null,
+                       "8a50b0b8c7654bced884f7f3afda2ead",
+                       null,
+                       "8e0f6d8bf05ffebe6f500eb1"),
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, 20-byte aad
+        new TestVector("2fb45e5b8f993a2bfebc4b15b533e0b4",
+                       "5b05755f984d2b90f94b8027",
+                       null,
+                       "e85491b2202caf1d7dce03b97e09331c32473941",
+                       null,
+                       "c75b7832b2a2d9bd827412b6ef5769db"),
+        new TestVector("9bf406339fcef9675bbcf156aa1a0661",
+                       "8be4a9543d40f542abacac95",
+                       null,
+                       "7167cbf56971793186333a6685bbd58d47d379b3",
+                       null,
+                       "5e7968d7bbd5ba58cfcc750e2ef8f1"),
+        new TestVector("a2e962fff70fd0f4d63be728b80556fc",
+                       "1fa7103483de43d09bc23db4",
+                       null,
+                       "2a58edf1d53f46e4e7ee5e77ee7aeb60fc360658",
+                       null,
+                       "fa37f2dbbefab1451eae1d0d74ca"),
+        new TestVector("6bf4fdce82926dcdfc52616ed5f23695",
+                       "cc0f5899a10615567e1193ed",
+                       null,
+                       "3340655592374c1da2f05aac3ee111014986107f",
+                       null,
+                       "8ad3385cce3b5e7c985908192c"),
+        new TestVector("4df7a13e43c3d7b66b1a72fac5ba398e",
+                       "97179a3a2d417908dcf0fb28",
+                       null,
+                       "cbb7fc0010c255661e23b07dbd804b1e06ae70ac",
+                       null,
+                       "37791edae6c137ea946cfb40"),
+        // 96-bit iv w/ 128-bit tags, 13/16/32/51-byte plain text, no aad
+        new TestVector("fe9bb47deb3a61e423c2231841cfd1fb",
+                       "4d328eb776f500a2f7fb47aa",
+                       "f1cc3818e421876bb6b8bbd6c9",
+                       null,
+                       "b88c5c1977b35b517b0aeae967",
+                       "43fd4727fe5cdb4b5b42818dea7ef8c9"),
+        new TestVector("7fddb57453c241d03efbed3ac44e371c",
+                       "ee283a3fc75575e33efd4887",
+                       "d5de42b461646c255c87bd2962d3b9a2",
+                       null,
+                       "2ccda4a5415cb91e135c2a0f78c9b2fd",
+                       "b36d1df9b9d5e596f83e8b7f52971cb3"),
+        new TestVector("9971071059abc009e4f2bd69869db338",
+                       "07a9a95ea3821e9c13c63251",
+                       "f54bc3501fed4f6f6dfb5ea80106df0bd836e6826225b75c0222f6e859b35983",
+                       null,
+                       "0556c159f84ef36cb1602b4526b12009c775611bffb64dc0d9ca9297cd2c6a01",
+                       "7870d9117f54811a346970f1de090c41"),
+        new TestVector("594157ec4693202b030f33798b07176d",
+                       "49b12054082660803a1df3df",
+
+"3feef98a976a1bd634f364ac428bb59cd51fb159ec1789946918dbd50ea6c9d594a3a31a5269b0da6936c29d063a5fa2cc8a1c",
+                      null,
+
+"c1b7a46a335f23d65b8db4008a49796906e225474f4fe7d39e55bf2efd97fd82d4167de082ae30fa01e465a601235d8d68bc69",
+                      "ba92d3661ce8b04687e8788d55417dc2"),
+        // 96-bit iv w/ 128-bit tags, 16-byte plain text, 16/20/48/90-byte aad
+        new TestVector("c939cc13397c1d37de6ae0e1cb7c423c",
+                       "b3d8cc017cbb89b39e0f67e2",
+                       "c3b3c41f113a31b73d9a5cd432103069",
+                       "24825602bd12a984e0092d3e448eda5f",
+                       "93fe7d9e9bfd10348a5606e5cafa7354",
+                       "0032a1dc85f1c9786925a2e71d8272dd"),
+        new TestVector("d4a22488f8dd1d5c6c19a7d6ca17964c",
+                       "f3d5837f22ac1a0425e0d1d5",
+                       "7b43016a16896497fb457be6d2a54122",
+                       "f1c5d424b83f96c6ad8cb28ca0d20e475e023b5a",
+                       "c2bd67eef5e95cac27e3b06e3031d0a8",
+                       "f23eacf9d1cdf8737726c58648826e9c"),
+        new TestVector("89850dd398e1f1e28443a33d40162664",
+                       "e462c58482fe8264aeeb7231",
+                       "2805cdefb3ef6cc35cd1f169f98da81a",
+
+"d74e99d1bdaa712864eec422ac507bddbe2b0d4633cd3dff29ce5059b49fe868526c59a2a3a604457bc2afea866e7606",
+                       "ba80e244b7fc9025cd031d0f63677e06",
+                       "d84a8c3eac57d1bb0e890a8f461d1065"),
+        new TestVector("bd7c5c63b7542b56a00ebe71336a1588",
+                       "87721f23ba9c3c8ea5571abc",
+                       "de15ddbb1e202161e8a79af6a55ac6f3",
+
+"a6ec8075a0d3370eb7598918f3b93e48444751624997b899a87fa6a9939f844e008aa8b70e9f4c3b1a19d3286bf543e7127bfecba1ad17a5ec53fccc26faecacc4c75369498eaa7d706aef634d0009279b11e4ba6c993e5e9ed9",
+                       "41eb28c0fee4d762de972361c863bc80",
+                       "9cb567220d0b252eb97bff46e4b00ff8"),
+        // 8/1024-bit iv w/ 128-bit tag, no plain text, no aad
+        new TestVector("1672c3537afa82004c6b8a46f6f0d026",
+                       "05",
+                       null, null, null,
+                       "8e2ad721f9455f74d8b53d3141f27e8e"),
+        new TestVector("d0f1f4defa1e8c08b4b26d576392027c",
+
+"42b4f01eb9f5a1ea5b1eb73b0fb0baed54f387ecaa0393c7d7dffc6af50146ecc021abf7eb9038d4303d91f8d741a11743166c0860208bcc02c6258fd9511a2fa626f96d60b72fcff773af4e88e7a923506e4916ecbd814651e9f445adef4ad6a6b6c7290cc13b956130eef5b837c939fcac0cbbcc9656cd75b13823ee5acdac",
+                       null, null, null,
+                       "7ab49b57ddf5f62c427950111c5c4f0d"),
+        // 8-bit iv w/ 128-bit tag, 13-byte plain text, 90-byte aad
+        new TestVector("9f79239f0904eace50784b863e723f6b",
+                       "d9",
+                       "bdb0bb10c87965acd34d146171",
+
+"44db436089327726c5f01139e1f339735c9e85514ccc2f167bad728010fb34a9072a9794c8a5e7361b1d0dbcdc9ac4091e354bb2896561f0486645252e9c78c86beece91bfa4f7cc4a8794ce1f305b1b735efdbf1ed1563c0be0",
+                       "7e5a7c8dadb3f0c7335b4d9d8d",
+                       "6b6ef1f53723a89f3bb7c6d043840717"),
+        // 1024-bit iv w/ 128-bit tag, 51-byte plain text, 48-byte aad
+        new TestVector("141f1ce91989b07e7eb6ae1dbd81ea5e",
+
+"49451da24bd6074509d3cebc2c0394c972e6934b45a1d91f3ce1d3ca69e194aa1958a7c21b6f21d530ce6d2cc5256a3f846b6f9d2f38df0102c4791e57df038f6e69085646007df999751e248e06c47245f4cd3b8004585a7470dee1690e9d2d63169a58d243c0b57b3e5b4a481a3e4e8c60007094ef3adea2e8f05dd3a1396f",
+
+"d384305af2388699aa302f510913fed0f2cb63ba42efa8c5c9de2922a2ec2fe87719dadf1eb0aef212b51e74c9c5b934104a43",
+
+"630cf18a91cc5a6481ac9eefd65c24b1a3c93396bd7294d6b8ba323951727666c947a21894a079ef061ee159c05beeb4",
+
+"f4c34e5fbe74c0297313268296cd561d59ccc95bbfcdfcdc71b0097dbd83240446b28dc088abd42b0fc687f208190ff24c0548",
+                      "dbb93bbb56d0439cd09f620a57687f5d"),
+    };
+
+    public boolean execute(TestVector[] testValues, Cipher c) throws Exception {
+        boolean testFailed = false;
+        for (int i = 0; i < testValues.length; i++) {
+            try {
+                c.init(Cipher.ENCRYPT_MODE, testValues[i].key, testValues[i].spec);
+                c.updateAAD(testValues[i].aad);
+                byte[] ctPlusTag = c.doFinal(testValues[i].plainText);
+
+                c.init(Cipher.DECRYPT_MODE, testValues[i].key, testValues[i].spec);
+                c.updateAAD(testValues[i].aad);
+                byte[] pt = c.doFinal(ctPlusTag); // should fail if tag mismatched
+
+                // check encryption/decryption results just to be sure
+                if (!Arrays.equals(testValues[i].plainText, pt)) {
+                    System.out.println("PlainText diff failed for test# " + i);
+                    testFailed = true;
+                }
+                int ctLen = testValues[i].cipherText.length;
+                if (!Arrays.equals(testValues[i].cipherText,
+                                   Arrays.copyOf(ctPlusTag, ctLen))) {
+                    System.out.println("CipherText diff failed for test# " + i);
+                    testFailed = true;
+                }
+                int tagLen = testValues[i].tag.length;
+                if (!Arrays.equals
+                    (testValues[i].tag,
+                     Arrays.copyOfRange(ctPlusTag, ctLen, ctLen+tagLen))) {
+                    System.out.println("Tag diff failed for test# " + i);
+                    testFailed = true;
+                }
+            } catch (Exception ex) {
+                // continue testing other test vectors
+                System.out.println("Failed Test Vector: " + testValues[i]);
+                ex.printStackTrace();
+                testFailed = true;
+                continue;
+            }
+        }
+        if (testFailed) {
+            throw new Exception("Test Failed");
+        }
+        // passed all tests...hooray!
+        return true;
+    }
+
+    public static void main(String[] args) throws Exception {
+        main(new TestKATForGCM(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        Cipher c;
+        String transformation = "AES/GCM/NoPadding";
+        try {
+            c = Cipher.getInstance(transformation, p);
+        } catch (GeneralSecurityException e) {
+            System.out.println("Skip testing " + p.getName() +
+                    ", no support for " + transformation);
+            return;
+        }
+        if (execute(testValues, c)) {
+            System.out.println("Test Passed!");
+        }
+    }
+}
+
--- a/test/jdk/sun/security/pkcs11/MessageDigest/ByteBuffers.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/security/pkcs11/MessageDigest/ByteBuffers.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,60 +23,74 @@
 
 /*
  * @test
- * @bug 4856966
+ * @bug 4856966 8080462
  * @summary Test the MessageDigest.update(ByteBuffer) method
  * @author Andreas Sterbenz
  * @library /test/lib ..
  * @key randomness
  * @modules jdk.crypto.cryptoki
  * @run main/othervm ByteBuffers
- * @run main/othervm ByteBuffers sm
  */
 
 import java.nio.ByteBuffer;
-import java.security.MessageDigest;
-import java.security.Provider;
+import java.security.*;
 import java.util.Arrays;
 import java.util.Random;
 
 public class ByteBuffers extends PKCS11Test {
 
+    static final String[] ALGS = {
+        "SHA-224", "SHA-256", "SHA-384", "SHA-512", "SHA-512/224", "SHA-512/256"
+    };
+
+    private static Random random = new Random();
+
     public static void main(String[] args) throws Exception {
         main(new ByteBuffers(), args);
     }
 
     @Override
     public void main(Provider p) throws Exception {
-        if (p.getService("MessageDigest", "MD5") == null) {
-            System.out.println("Provider does not support MD5, skipping");
-            return;
-        }
-
-        Random random = new Random();
         int n = 10 * 1024;
         byte[] t = new byte[n];
         random.nextBytes(t);
 
-        MessageDigest md = MessageDigest.getInstance("MD5", p);
-        byte[] d1 = md.digest(t);
+        for (String alg : ALGS) {
+            runTest(p, alg, t);
+        }
+    }
+
+    private void runTest(Provider p, String alg, byte[] data) throws Exception {
+        System.out.println("Test against " + p.getName() + " and " + alg);
+        MessageDigest md;
+        try {
+            md = MessageDigest.getInstance(alg, p);
+        } catch (NoSuchAlgorithmException e) {
+            System.out.println("Skip " + alg + " due to no support");
+            return;
+        }
+
+        byte[] d1 = md.digest(data);
+
+        int n = data.length;
 
         // test 1: ByteBuffer with an accessible backing array
         ByteBuffer b1 = ByteBuffer.allocate(n + 256);
         b1.position(random.nextInt(256));
         b1.limit(b1.position() + n);
         ByteBuffer b2 = b1.slice();
-        b2.put(t);
+        b2.put(data);
         b2.clear();
-        byte[] d2 = digest(md, b2, random);
+        byte[] d2 = digest(md, b2);
         if (Arrays.equals(d1, d2) == false) {
             throw new Exception("Test 1 failed");
         }
 
         // test 2: direct ByteBuffer
-        ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);
-        b3.put(t);
+        ByteBuffer b3 = ByteBuffer.allocateDirect(n);
+        b3.put(data);
         b3.clear();
-        byte[] d3 = digest(md, b3, random);
+        byte[] d3 = digest(md, b3);
         if (Arrays.equals(d1, d2) == false) {
             throw new Exception("Test 2 failed");
         }
@@ -84,14 +98,15 @@
         // test 3: ByteBuffer without an accessible backing array
         b2.clear();
         ByteBuffer b4 = b2.asReadOnlyBuffer();
-        byte[] d4 = digest(md, b4, random);
+        byte[] d4 = digest(md, b4);
         if (Arrays.equals(d1, d2) == false) {
             throw new Exception("Test 3 failed");
         }
         System.out.println("All tests passed");
     }
 
-    private static byte[] digest(MessageDigest md, ByteBuffer b, Random random) throws Exception {
+    private static byte[] digest(MessageDigest md, ByteBuffer b)
+            throws Exception {
         int lim = b.limit();
         b.limit(random.nextInt(lim));
         md.update(b);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Signature/InitAgainPSS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.security.*;
+import java.security.spec.*;
+
+/**
+ * @test
+ * @bug 8080462
+ * @summary Make sure old state is cleared when init is called again
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ */
+public class InitAgainPSS extends PKCS11Test {
+
+    public static void main(String[] args) throws Exception {
+        main(new InitAgainPSS(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        Signature s1;
+        try {
+            s1 = Signature.getInstance("RSASSA-PSS", p);
+        } catch (NoSuchAlgorithmException e) {
+            System.out.println("Skip testing RSASSA-PSS" +
+                " due to no support");
+            return;
+        }
+
+        byte[] msg = "hello".getBytes();
+
+        Signature s2 = Signature.getInstance("RSASSA-PSS", p);
+
+        PSSParameterSpec params = new PSSParameterSpec("SHA-256", "MGF1",
+            new MGF1ParameterSpec("SHA-256"), 32,
+            PSSParameterSpec.TRAILER_FIELD_BC);
+        s1.setParameter(params);
+        s2.setParameter(params);
+
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
+        kpg.initialize(2048);
+        KeyPair kp = kpg.generateKeyPair();
+
+        s1.initSign(kp.getPrivate());
+
+        s1.update(msg);
+        s1.initSign(kp.getPrivate());
+        s1.update(msg);
+        // Data digested in s1:
+        // Before this fix, msg | msg
+        // After this fix, msg
+
+        s2.initVerify(kp.getPublic());
+        s2.update(msg);
+        s2.initVerify(kp.getPublic());
+        s2.update(msg);
+        s2.initVerify(kp.getPublic());
+        s2.update(msg);
+        // Data digested in s2:
+        // Before this fix, msg | msg | msg
+        // After this fix, msg
+
+        if (!s2.verify(s1.sign())) {
+            throw new Exception();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Signature/KeyAndParamCheckForPSS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.security.*;
+import java.security.interfaces.*;
+import java.security.spec.*;
+
+/**
+ * @test
+ * @bug 8080462
+ * @summary Ensure that PSS key and params check are implemented properly
+ *         regardless of call sequence
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main KeyAndParamCheckForPSS
+ */
+public class KeyAndParamCheckForPSS extends PKCS11Test {
+
+    /**
+     * ALGORITHM name, fixed as RSA for PKCS11
+     */
+    private static final String KEYALG = "RSA";
+    private static final String SIGALG = "RSASSA-PSS";
+
+    public static void main(String[] args) throws Exception {
+        main(new KeyAndParamCheckForPSS(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        Signature sig;
+        try {
+            sig = Signature.getInstance(SIGALG, p);
+        } catch (NoSuchAlgorithmException e) {
+            System.out.println("Skip testing RSASSA-PSS" +
+                " due to no support");
+            return;
+        }
+        // NOTE: key length >= (digest length + 2) in bytes
+        // otherwise, even salt length = 0 would not work
+        runTest(p, 1024, "SHA-384");
+        runTest(p, 1040, "SHA-512");
+    }
+
+    private void runTest(Provider p, int keySize, String hashAlg)
+            throws Exception {
+        System.out.println("Testing [" + keySize + " " + hashAlg + "]");
+
+        // create a key pair with the supplied size
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEYALG, p);
+        kpg.initialize(keySize);
+        KeyPair kp = kpg.generateKeyPair();
+
+        int bigSaltLen = keySize/8 - 14;
+        AlgorithmParameterSpec paramsBad = new PSSParameterSpec(hashAlg,
+            "MGF1", new MGF1ParameterSpec(hashAlg), bigSaltLen, 1);
+        AlgorithmParameterSpec paramsGood = new PSSParameterSpec(hashAlg,
+            "MGF1", new MGF1ParameterSpec(hashAlg), 0, 1);
+
+        PrivateKey priv = kp.getPrivate();
+        PublicKey pub = kp.getPublic();
+
+        // test#1 - setParameter then initSign
+        Signature sig = Signature.getInstance("RSASSA-PSS", p);
+        sig.setParameter(paramsBad);
+        try {
+            sig.initSign(priv);
+            throw new RuntimeException("Expected IKE not thrown");
+        } catch (InvalidKeyException ike) {
+            System.out.println("test#1: got expected IKE");
+        }
+        sig.setParameter(paramsGood);
+        sig.initSign(priv);
+        System.out.println("test#1: pass");
+
+        // test#2 - setParameter then initVerify
+        sig = Signature.getInstance("RSASSA-PSS", p);
+        sig.setParameter(paramsBad);
+        try {
+            sig.initVerify(pub);
+            throw new RuntimeException("Expected IKE not thrown");
+        } catch (InvalidKeyException ike) {
+            System.out.println("test#2: got expected IKE");
+        }
+        sig.setParameter(paramsGood);
+        sig.initVerify(pub);
+        System.out.println("test#2: pass");
+
+        // test#3 - initSign, then setParameter
+        sig = Signature.getInstance("RSASSA-PSS", p);
+        sig.initSign(priv);
+        try {
+            sig.setParameter(paramsBad);
+            throw new RuntimeException("Expected IAPE not thrown");
+        } catch (InvalidAlgorithmParameterException iape) {
+            System.out.println("test#3: got expected IAPE");
+        }
+        sig.setParameter(paramsGood);
+        System.out.println("test#3: pass");
+
+        // test#4 - initVerify, then setParameter
+        sig = Signature.getInstance("RSASSA-PSS", p);
+        sig.initVerify(pub);
+        try {
+            sig.setParameter(paramsBad);
+            throw new RuntimeException("Expected IAPE not thrown");
+        } catch (InvalidAlgorithmParameterException iape) {
+            System.out.println("test#4: got expected IAPE");
+        }
+        sig.setParameter(paramsGood);
+        System.out.println("test#4: pass");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Signature/SigInteropPSS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.security.*;
+import java.security.spec.*;
+import java.security.interfaces.*;
+
+/*
+ * @test
+ * @bug 8080462
+ * @summary testing interoperability of PSS signatures of PKCS11 provider
+ *         against SunRsaSign provider
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main/othervm SigInteropPSS
+ */
+public class SigInteropPSS extends PKCS11Test {
+
+    private static final byte[] MSG =
+        "Interoperability test between SunRsaSign and SunPKCS11".getBytes();
+
+    private static final String[] DIGESTS = {
+        "SHA-224", "SHA-256", "SHA-384", "SHA-512"
+    };
+
+    public static void main(String[] args) throws Exception {
+        main(new SigInteropPSS(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        Signature sigPkcs11;
+        try {
+            sigPkcs11 = Signature.getInstance("RSASSA-PSS", p);
+        } catch (NoSuchAlgorithmException e) {
+            System.out.println("Skip testing RSASSA-PSS" +
+                " due to no support");
+            return;
+        }
+
+        Signature sigSunRsaSign =
+                Signature.getInstance("RSASSA-PSS", "SunRsaSign");
+
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
+        kpg.initialize(3072);
+        KeyPair kp = kpg.generateKeyPair();
+        boolean status;
+        try {
+            status = runTest(sigSunRsaSign, sigPkcs11, kp);
+            status &= runTest(sigPkcs11, sigSunRsaSign, kp);
+        } catch (Exception e) {
+            System.out.println("Unexpected exception: " + e);
+            e.printStackTrace(System.out);
+            status = false;
+        }
+
+        if (!status) {
+            throw new RuntimeException("One or more test failed");
+        }
+        System.out.println("Test passed");
+    }
+
+    static boolean runTest(Signature signer, Signature verifier, KeyPair kp) throws Exception {
+        System.out.println("\tSign using " + signer.getProvider().getName());
+        System.out.println("\tVerify using " + verifier.getProvider().getName());
+
+        boolean status;
+        for (String digestAlg : DIGESTS) {
+            System.out.println("\tDigest = " + digestAlg);
+            PSSParameterSpec params = new PSSParameterSpec(digestAlg, "MGF1",
+                    new MGF1ParameterSpec(digestAlg), 0, 1);
+            try {
+                signer.setParameter(params);
+                signer.initSign(kp.getPrivate());
+                verifier.setParameter(params);
+                verifier.initVerify(kp.getPublic());
+            } catch (Exception e) {
+                System.out.println("\tERROR: unexpected ex during init" + e);
+                status = false;
+                continue;
+            }
+            try {
+                signer.update(MSG);
+                byte[] sigBytes = signer.sign();
+                verifier.update(MSG);
+                boolean isValid = verifier.verify(sigBytes);
+                if (isValid) {
+                    System.out.println("\tPSS Signature verified");
+                } else {
+                    System.out.println("\tERROR verifying PSS Signature");
+                    status = false;
+                }
+            } catch (Exception e) {
+                System.out.println("\tERROR: unexpected ex" + e);
+                e.printStackTrace();
+                status = false;
+            }
+        }
+        return true;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Signature/SignatureTestPSS.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.security.*;
+import java.security.interfaces.*;
+import java.security.spec.*;
+import java.util.stream.IntStream;
+
+/**
+ * @test
+ * @bug 8080462
+ * @summary Generate a RSASSA-PSS signature and verify it using PKCS11 provider
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main SignatureTestPSS
+ */
+public class SignatureTestPSS extends PKCS11Test {
+
+    // PKCS11 does not support RSASSA-PSS keys yet
+    private static final String KEYALG = "RSA";
+    private static final String SIGALG = "RSASSA-PSS";
+
+    private static final int[] KEYSIZES = { 2048, 3072 };
+    private static final String[] DIGESTS = { "SHA-224", "SHA-256",
+            "SHA-384" , "SHA-512" };
+    private Provider prov;
+
+    /**
+     * How much times signature updated.
+     */
+    private static final int UPDATE_TIMES_FIFTY = 50;
+
+    /**
+     * How much times signature initial updated.
+     */
+    private static final int UPDATE_TIMES_HUNDRED = 100;
+
+    public static void main(String[] args) throws Exception {
+        main(new SignatureTestPSS(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        Signature sig;
+        try {
+            sig = Signature.getInstance(SIGALG, p);
+        } catch (NoSuchAlgorithmException e) {
+            System.out.println("Skip testing RSASSA-PSS" +
+                " due to no support");
+            return;
+        }
+        this.prov = p;
+        for (int i : KEYSIZES) {
+            runTest(i);
+        }
+    }
+
+    private void runTest(int keySize) throws Exception {
+        byte[] data = new byte[100];
+        IntStream.range(0, data.length).forEach(j -> {
+            data[j] = (byte) j;
+        });
+        System.out.println("[KEYSIZE = " + keySize + "]");
+
+        // create a key pair
+        KeyPair kpair = generateKeys(KEYALG, keySize);
+        test(DIGESTS, kpair.getPrivate(), kpair.getPublic(), data);
+    }
+
+    private void test(String[] testAlgs, PrivateKey privKey,
+            PublicKey pubKey, byte[] data) throws RuntimeException {
+        // For signature algorithm, create and verify a signature
+        for (String testAlg : testAlgs) {
+            try {
+                checkSignature(data, pubKey, privKey, testAlg);
+            } catch (NoSuchAlgorithmException | InvalidKeyException |
+                     SignatureException | NoSuchProviderException ex) {
+                throw new RuntimeException(ex);
+            } catch (InvalidAlgorithmParameterException ex2) {
+                System.out.println("Skip test due to " + ex2);
+            }
+        };
+    }
+
+    private KeyPair generateKeys(String keyalg, int size)
+            throws NoSuchAlgorithmException {
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyalg, prov);
+        kpg.initialize(size);
+        return kpg.generateKeyPair();
+    }
+
+    private void checkSignature(byte[] data, PublicKey pub,
+            PrivateKey priv, String mdAlg) throws NoSuchAlgorithmException,
+            InvalidKeyException, SignatureException, NoSuchProviderException,
+            InvalidAlgorithmParameterException {
+        System.out.println("Testing against " + mdAlg);
+        Signature sig = Signature.getInstance(SIGALG, prov);
+        AlgorithmParameterSpec params = new PSSParameterSpec(
+            mdAlg, "MGF1", new MGF1ParameterSpec(mdAlg), 0, 1);
+        sig.setParameter(params);
+        sig.initSign(priv);
+        for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
+            sig.update(data);
+        }
+        byte[] signedData = sig.sign();
+
+        // Make sure signature verifies with original data
+        // do we need to call sig.setParameter(params) again?
+        sig.initVerify(pub);
+        for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
+            sig.update(data);
+        }
+        if (!sig.verify(signedData)) {
+            throw new RuntimeException("Failed to verify signature");
+        }
+
+        // Make sure signature does NOT verify when the original data
+        // has changed
+        sig.initVerify(pub);
+        for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) {
+            sig.update(data);
+        }
+
+        if (sig.verify(signedData)) {
+            throw new RuntimeException("Failed to detect bad signature");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/pkcs11/Signature/TestDSA2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8080462
+ * @library /test/lib ..
+ * @modules jdk.crypto.cryptoki
+ * @run main/othervm/timeout=250 TestDSA2
+ * @summary verify that DSA signature works using SHA-2 digests.
+ * @key randomness
+ */
+
+
+import java.security.*;
+import java.security.spec.*;
+import java.security.interfaces.*;
+
+public class TestDSA2 extends PKCS11Test {
+
+    private static final String[] SIG_ALGOS = {
+        "SHA224withDSA",
+        "SHA256withDSA",
+        //"SHA384withDSA",
+        //"SHA512withDSA",
+    };
+
+    private static final int KEYSIZE = 2048;
+
+    public static void main(String[] args) throws Exception {
+        main(new TestDSA2(), args);
+    }
+
+    @Override
+    public void main(Provider p) throws Exception {
+        KeyPair kp;
+        try {
+            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", p);
+            kpg.initialize(KEYSIZE);
+            kp = kpg.generateKeyPair();
+        } catch (Exception ex) {
+            System.out.println("Skip due to no 2048-bit DSA support: " + ex);
+            ex.printStackTrace();
+            return;
+        }
+
+        for (String sigAlg : SIG_ALGOS) {
+            test(sigAlg, kp, p);
+        }
+    }
+
+    private static void test(String sigAlg, KeyPair kp, Provider p)
+            throws Exception {
+        Signature sig;
+        try {
+            sig = Signature.getInstance(sigAlg, p);
+        } catch (Exception ex) {
+            System.out.println("Skip due to no support: " + sigAlg);
+            ex.printStackTrace();
+            return;
+        }
+
+        byte[] data = "anything will do".getBytes();
+
+        sig.initSign(kp.getPrivate());
+        sig.update(data);
+        byte[] signature = sig.sign();
+
+        sig.initVerify(kp.getPublic());
+        sig.update(data);
+        boolean verifies = sig.verify(signature);
+        System.out.println(sigAlg + ": Passed");
+    }
+}
--- a/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java	Wed Jun 12 10:02:49 2019 +0530
@@ -30,44 +30,57 @@
  * @test
  * @bug 6956398
  * @summary make ephemeral DH key match the length of the certificate key
- * @run main/othervm
+ * @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1643 267
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=matched
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=legacy
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=1024
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  *
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA true 233 75
  *
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1387 139
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=legacy
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1323 107
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=matched
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1643 267
  * @run main/othervm -Djsse.enableFFDHE=false
  *      -Djdk.tls.ephemeralDHKeySize=1024
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1387 139
  *
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      -Djdk.tls.ephemeralDHKeySize=legacy
  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 297 107
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      -Djdk.tls.ephemeralDHKeySize=matched
  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  * @run main/othervm -Djsse.enableFFDHE=false
+ *      -Djdk.tls.client.enableSessionTicketExtension=false
  *      -Djdk.tls.ephemeralDHKeySize=1024
  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  */
--- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,13 +26,17 @@
  * @bug 8206929 8212885
  * @summary ensure that client only resumes a session if certain properties
  *    of the session are compatible with the new connection
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 ResumeChecksClient BASIC
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksClient BASIC
- * @run main/othervm ResumeChecksClient BASIC
- * @run main/othervm ResumeChecksClient VERSION_2_TO_3
- * @run main/othervm ResumeChecksClient VERSION_3_TO_2
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksClient CIPHER_SUITE
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksClient SIGNATURE_SCHEME
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient VERSION_2_TO_3
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient VERSION_3_TO_2
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient CIPHER_SUITE
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient SIGNATURE_SCHEME
  *
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClientStateless.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8211018
+ * @summary ensure that client only resumes a session if certain properties
+ *    of the session are compatible with the new connection
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient VERSION_2_TO_3
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient VERSION_3_TO_2
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient CIPHER_SUITE
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient SIGNATURE_SCHEME
+ */
--- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,16 +26,18 @@
  * @bug 8206929
  * @summary ensure that server only resumes a session if certain properties
  *    of the session are compatible with the new connection
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 ResumeChecksServer BASIC
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer BASIC
- * @run main/othervm ResumeChecksServer BASIC
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 ResumeChecksServer CLIENT_AUTH
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CLIENT_AUTH
- * @run main/othervm ResumeChecksServer CLIENT_AUTH
- * @run main/othervm ResumeChecksServer VERSION_2_TO_3
- * @run main/othervm ResumeChecksServer VERSION_3_TO_2
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CIPHER_SUITE
- * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer SIGNATURE_SCHEME
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer CLIENT_AUTH
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer CLIENT_AUTH
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer CLIENT_AUTH
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer VERSION_2_TO_3
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer VERSION_2_TO_3
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer VERSION_2_TO_3
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer VERSION_3_TO_2
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer VERSION_3_TO_2
+ * @run main/othervm -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer VERSION_3_TO_2
  *
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServerStateless.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8211018
+ * @summary ensure that server only resumes a session if certain properties
+ *    of the session are compatible with the new connection
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer BASIC
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CLIENT_AUTH
+ * @run main/othervm ResumeChecksServer VERSION_2_TO_3
+ * @run main/othervm ResumeChecksServer VERSION_3_TO_2
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CIPHER_SUITE
+ * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer SIGNATURE_SCHEME
+ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/JavaKeyStoreAliasCaseInsensitive.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8221719
+ * @library /test/lib
+ * @run testng JavaKeyStoreAliasCaseInsensitive
+ * @summary Checks that jarsigner verifies a signed jar with the same alias as
+ * was specified for signing, particularly regarding upper and lower case and
+ * its conversion to lower case by JKS
+ * ({@link sun.security.provider.JavaKeyStore.JKS#convertAlias(String)}).
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import jdk.test.lib.util.JarUtils;
+import jdk.test.lib.SecurityTools;
+import org.testng.annotations.Test;
+
+public class JavaKeyStoreAliasCaseInsensitive {
+
+    /**
+     * Alias for certificates in the keystore with letters in different
+     * (upper and lower) cases.
+     */
+    static final String ALIAS = "AlIaS";
+
+    @Test
+    public void testAliasCase() throws Exception {
+        final String KEYSTORE_OPTIONS = "-storetype JKS -keystore "
+                + "test-alias-case.jks -storepass changeit";
+        SecurityTools.keytool(KEYSTORE_OPTIONS + " -genkeypair"
+                + " -keypass changeit -alias " + ALIAS + " -dname CN=" + ALIAS)
+                .shouldHaveExitValue(0);
+        String jarFilename = "test-alias-case.jar";
+        JarUtils.createJarFile(Paths.get(jarFilename), Paths.get("."),
+                Files.write(Paths.get("aFile"), new byte[1]));
+
+        SecurityTools.jarsigner(KEYSTORE_OPTIONS + " -verbose -debug " +
+                jarFilename + " " + ALIAS).shouldHaveExitValue(0);
+
+        SecurityTools.jarsigner("-verify -strict " + KEYSTORE_OPTIONS +
+                " -debug -verbose " + jarFilename + " " + ALIAS)
+                .shouldHaveExitValue(0)
+                .shouldNotContain(
+                        "This jar contains signed entries which are not "
+                        + "signed by the specified alias(es).");
+    }
+
+    /**
+     * This test essentially covers compatibility with the previous version of
+     * {@link sun.security.tools.jarsigner.Main#inKeyStoreForOneSigner} in case
+     * a certificate and alias entry is already in
+     * {@link sun.security.tools.jarsigner.Main#storeHash} when
+     * {@link sun.security.tools.jarsigner.Main#inKeyStoreForOneSigner} is
+     * invoked from a previous invocation of it.
+     * It passed with the previous {@code jarsigner} version with a lowercase
+     * alias {@link #ALIAS} and basically covers the duplicated portions of
+     * code in {@link sun.security.tools.jarsigner.Main#inKeyStoreForOneSigner}
+     * near {@code IN_KEYSTORE} and {@code SIGNED_BY_ALIAS} before having
+     * refactored and re-unified them in order to demonstrate identical
+     * behavior.
+     */
+    @Test
+    public void testAliasCaseStoreHash() throws Exception {
+        // Create a keystore with a certificate associated with ALIAS + "2"
+        // signed by another certificate associated with ALIAS + "1".
+        final String KEYSTORE_OPTIONS = "-storetype JKS -keystore"
+                + " test-alias-storeHash-case.jks -storepass changeit";
+        SecurityTools.keytool(KEYSTORE_OPTIONS + " -genkeypair"
+                + " -keypass changeit -alias " + ALIAS + "1 -dname CN=" +
+                ALIAS + "1").shouldHaveExitValue(0);
+        SecurityTools.keytool(KEYSTORE_OPTIONS + " -genkeypair"
+                + " -keypass changeit -alias " + ALIAS + "2 -dname CN="
+                + ALIAS + "2").shouldHaveExitValue(0);
+        String certReq = SecurityTools.keytool(KEYSTORE_OPTIONS +
+                " -certreq -keypass changeit -alias " + ALIAS + "2")
+                .shouldHaveExitValue(0).getStdout();
+        SecurityTools.setResponse(certReq);
+        String cert = SecurityTools.keytool(KEYSTORE_OPTIONS +
+                " -gencert -rfc -keypass changeit -alias " + ALIAS + "1")
+                .shouldHaveExitValue(0).getOutput();
+        SecurityTools.setResponse(cert);
+        SecurityTools.keytool(KEYSTORE_OPTIONS +
+                " -importcert -keypass changeit -alias " + ALIAS + "2")
+                .shouldHaveExitValue(0);
+
+        // Create a jar file signed by ALIAS + "2" and then add another file to
+        // that same jar and sign it by ALIAS + "1", ALIAS + "1" being an alias
+        // for a certificate which is part of the certificate chain of ALIAS +
+        // "2" but not the certificate ALIAS + "2" points to directly.
+        String jarFilename = "test-alias-storeHash-case.jar";
+        JarUtils.createJarFile(Paths.get(jarFilename), Paths.get("."));
+        SecurityTools.jarsigner(KEYSTORE_OPTIONS + " -verbose -debug " +
+                jarFilename + " " + ALIAS + "2").shouldHaveExitValue(0);
+        JarUtils.updateJarFile(Paths.get(jarFilename), Paths.get("."),
+                Files.write(Paths.get("added-file"), new byte[1]));
+        SecurityTools.jarsigner(KEYSTORE_OPTIONS + " -verbose -debug " +
+                jarFilename + " " + ALIAS + "1").shouldHaveExitValue(0);
+
+        // The later added file "added-file" is signed by the certificate
+        // associated with alias ALIAS + "1" directly while the other jarfile
+        // contents is signed by a certificate associated with alias ALIAS + "2"
+        // which includes the certificate associated with alias ALIAS + "1" in
+        // its certification path.
+        SecurityTools.jarsigner("-verify -strict " + KEYSTORE_OPTIONS +
+                " -debug -verbose " + jarFilename + " " + ALIAS + "1")
+                .shouldHaveExitValue(0)
+                .shouldNotContain(
+                        "This jar contains signed entries which are not "
+                        + "signed by the specified alias(es).");
+    }
+
+}
--- a/test/langtools/tools/javac/diags/examples/BracketsNotAllowedImplicitLambda.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/BracketsNotAllowedImplicitLambda.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.err.var.not.allowed.array
+// key: compiler.err.restricted.type.not.allowed.array
 
 import java.util.function.*;
 
--- a/test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// key: compiler.err.break.ambiguous.target
-// key: compiler.note.preview.filename
-// key: compiler.note.preview.recompile
-// options: --enable-preview -source ${jdk.version}
-
-class BreakAmbiguousTarget {
-    void m(int i, int j) {
-        j: print(switch (i) {
-            default: break j;
-        });
-    }
-    void print(int i) { }
-}
--- a/test/langtools/tools/javac/diags/examples/BreakComplexValueNoSwitchExpression.java	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// key: compiler.err.break.complex.value.no.switch.expression
-
-class BreakComplexValueNoSwitchExpressions {
-    void t() {
-        while (true) {
-            break 1 + 1;
-        }
-    }
-}
--- a/test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// key: compiler.err.break.expr.not.immediate
-// key: compiler.misc.tree.tag.doloop
-// key: compiler.misc.tree.tag.foreachloop
-// key: compiler.misc.tree.tag.forloop
-// key: compiler.misc.tree.tag.switch
-// key: compiler.misc.tree.tag.whileloop
-// key: compiler.note.note
-// key: compiler.err.error
-// key: compiler.misc.count.error.plural
-// key: compiler.note.preview.filename
-// key: compiler.note.preview.recompile
-// key: compiler.note.note
-// options: --enable-preview -source ${jdk.version}
-// run: backdoor
-
-class BreakExprNotImmediate {
-    int t(int i) {
-        return switch (i) {
-            case 0:
-                for (; ;) {
-                    break 1 + 1;
-                }
-            case 1:
-                for (String s : new String[0]) {
-                    break 1 + 1;
-                }
-            case 2:
-                while (true) {
-                    break 1 + 1;
-                }
-            case 3:
-                do {
-                    break 1 + 1;
-                } while (true);
-            case 4:
-                switch (i) {
-                    default: break 1 + 1;
-                }
-                break 0;
-        };
-    }
-}
--- a/test/langtools/tools/javac/diags/examples/BreakMissingValue.java	Tue Jun 11 17:15:25 2019 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// key: compiler.err.break.missing.value
-// key: compiler.note.preview.filename
-// key: compiler.note.preview.recompile
-// options: --enable-preview -source ${jdk.version}
-
-class BreakMissingValue {
-    int t(int i) {
-        return switch (i) {
-            default: break;
-        };
-    }
-}
--- a/test/langtools/tools/javac/diags/examples/FutureVarNotAllowed.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/FutureVarNotAllowed.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.warn.var.not.allowed
+// key: compiler.warn.restricted.type.not.allowed
 // options: --release 9
 
 class var { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/IllegalRefToRestrictedType.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.warn.illegal.ref.to.restricted.type
+// key: compiler.warn.restricted.type.not.allowed.preview
+
+class IllegalRefToVarType {
+    yield list() { return null; }
+    public class yield {}
+}
--- a/test/langtools/tools/javac/diags/examples/IllegalRefToVarType.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/IllegalRefToVarType.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.err.illegal.ref.to.var.type
+// key: compiler.err.illegal.ref.to.restricted.type
 
 import java.util.List;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/InvalidYield.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.err.invalid.yield
+// options: --enable-preview --source 13
+
+class BreakComplexValueNoSwitchExpressions {
+    void t() {
+        while (true) {
+            yield(1, 2);
+        }
+    }
+    private void yield(int i, int j) {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/InvalidYieldWarning.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.warn.invalid.yield
+// options: --source 13
+
+class BreakComplexValueNoSwitchExpressions {
+    void t() {
+        while (true) {
+            yield(1, 2);
+        }
+    }
+    private void yield(int i, int j) {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/NoSwitchExpression.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.err.no.switch.expression
+// options: --enable-preview --source 13
+
+class BreakComplexValueNoSwitchExpressions {
+    void t() {
+        while (true) {
+            yield 1 + 1;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/NoSwitchExpressionQualify.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.err.no.switch.expression.qualify
+// options: --enable-preview --source 13
+
+class BreakComplexValueNoSwitchExpressions {
+    void t() {
+        while (true) {
+            yield(1 + 1);
+        }
+    }
+    private void yield(int i) {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/RestrictedTypeNotAllowedPreview.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.warn.restricted.type.not.allowed.preview
+
+class yield { }
--- a/test/langtools/tools/javac/diags/examples/SwitchExpressions.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/SwitchExpressions.java	Wed Jun 12 10:02:49 2019 +0530
@@ -28,7 +28,7 @@
 class SwitchExpressions {
     int m(int i) {
         return switch (i) {
-            default: break -1;
+            default: yield -1;
         };
     }
 }
--- a/test/langtools/tools/javac/diags/examples/VarNotAllowed.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/VarNotAllowed.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,6 +21,6 @@
  * questions.
  */
 
-// key: compiler.err.var.not.allowed
+// key: compiler.err.restricted.type.not.allowed
 
 class var { }
--- a/test/langtools/tools/javac/diags/examples/VarNotAllowedArray.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/VarNotAllowedArray.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.err.var.not.allowed.array
+// key: compiler.err.restricted.type.not.allowed.array
 
 class VarNotAllowedArray {
     void test(String[] s) {
--- a/test/langtools/tools/javac/diags/examples/VarNotAllowedCompound.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/VarNotAllowedCompound.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.err.var.not.allowed.compound
+// key: compiler.err.restricted.type.not.allowed.compound
 
 class VarNotAllowedCompound {
     void test() {
--- a/test/langtools/tools/javac/diags/examples/VarNotAllowedHere.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/diags/examples/VarNotAllowedHere.java	Wed Jun 12 10:02:49 2019 +0530
@@ -21,7 +21,7 @@
  * questions.
  */
 
-// key: compiler.err.var.not.allowed.here
+// key: compiler.err.restricted.type.not.allowed.here
 
 class VarNotAllowedField {
     var s = "";
--- a/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -48,11 +48,12 @@
     private static final String INT_ESWITCH_DEFAULT = "int res = switch (x) { default -> { # } };";
     private static final String IF = "if (cond) { # } else throw new RuntimeException();";
     private static final String BLOCK = "{ # }";
-    private static final String BREAK_Z = "break 0;";
-    private static final String BREAK_S = "break \"hello world\";";
-    private static final String BREAK_INT_FN = "break () -> 0 ;";
+    private static final String YIELD_Z = "yield 0;";
+    private static final String YIELD_S = "yield \"hello world\";";
+    private static final String YIELD_INT_FN = "yield () -> 0 ;";
     private static final String BREAK_N = "break;";
     private static final String BREAK_L = "break label;";
+    private static final String YIELD_L = "yield label;";
     private static final String RETURN_Z = "return 0;";
     private static final String RETURN_N = "return;";
     private static final String RETURN_S = "return \"Hello\";";
@@ -136,11 +137,11 @@
         assertOK(RUNNABLE, NOTHING);
         assertOK(INT_FN, RETURN_Z);
         assertFail("compiler.err.break.outside.switch.loop", RUNNABLE, BREAK_N);
-        assertFail("compiler.err.break.complex.value.no.switch.expression", RUNNABLE, BREAK_Z);
-        assertFail("compiler.err.break.complex.value.no.switch.expression", RUNNABLE, BREAK_S);
+        assertFail("compiler.err.no.switch.expression", RUNNABLE, YIELD_Z);
+        assertFail("compiler.err.no.switch.expression", RUNNABLE, YIELD_S);
         assertFail("compiler.err.break.outside.switch.loop", INT_FN, BREAK_N);
-        assertFail("compiler.err.break.complex.value.no.switch.expression", INT_FN, BREAK_Z);
-        assertFail("compiler.err.break.complex.value.no.switch.expression", INT_FN, BREAK_S);
+        assertFail("compiler.err.no.switch.expression", INT_FN, YIELD_Z);
+        assertFail("compiler.err.no.switch.expression", INT_FN, YIELD_S);
         assertFail("compiler.err.cont.outside.loop", RUNNABLE, CONTINUE_N);
         assertFail("compiler.err.undef.label", RUNNABLE, BREAK_L);
         assertFail("compiler.err.undef.label", RUNNABLE, CONTINUE_L);
@@ -155,92 +156,94 @@
 
     public void testEswitch() {
         //Int-valued switch expressions
-        assertOK(ESWITCH_Z, BREAK_Z);
-        assertOK(LABEL, BLOCK, ESWITCH_Z, BREAK_Z);
-        assertFail("compiler.err.break.missing.value", ESWITCH_Z, BREAK_N);
-        assertFail("compiler.err.prob.found.req", ESWITCH_Z, BREAK_S);
-        assertFail("compiler.err.cant.resolve.location", ESWITCH_Z, BREAK_L);
+        assertOK(ESWITCH_Z, YIELD_Z);
+        assertOK(LABEL, BLOCK, ESWITCH_Z, YIELD_Z);
+        assertFail("compiler.err.break.outside.switch.expression", ESWITCH_Z, BREAK_N);
+        assertFail("compiler.err.prob.found.req", ESWITCH_Z, YIELD_S);
+        assertFail("compiler.err.undef.label", ESWITCH_Z, BREAK_L);
         assertFail("compiler.err.break.outside.switch.expression", LABEL, BLOCK, ESWITCH_Z, BREAK_L);
         assertFail("compiler.err.undef.label", ESWITCH_Z, CONTINUE_L);
-        assertFail("compiler.err.cont.outside.loop", ESWITCH_Z, CONTINUE_N);
+        assertFail("compiler.err.continue.outside.switch.expression", ESWITCH_Z, CONTINUE_N);
         assertFail("compiler.err.return.outside.switch.expression", ESWITCH_Z, RETURN_N);
         assertFail("compiler.err.return.outside.switch.expression", ESWITCH_Z, RETURN_Z);
 
-        assertOK(INT_ESWITCH_DEFAULT, BREAK_Z);
-        assertFail("compiler.err.break.missing.value", INT_ESWITCH_DEFAULT, BREAK_N);
-        assertFail("compiler.err.prob.found.req", INT_ESWITCH_DEFAULT, BREAK_S);
-        assertFail("compiler.err.cant.resolve.location", INT_ESWITCH_DEFAULT, BREAK_L);
+        assertOK(INT_ESWITCH_DEFAULT, YIELD_Z);
+        assertFail("compiler.err.break.outside.switch.expression", INT_ESWITCH_DEFAULT, BREAK_N);
+        assertFail("compiler.err.prob.found.req", INT_ESWITCH_DEFAULT, YIELD_S);
+        assertFail("compiler.err.undef.label", INT_ESWITCH_DEFAULT, BREAK_L);
 
 
         // String-valued switch expressions
-        assertOK(ESWITCH_S, BREAK_S);
-        assertOK(LABEL, BLOCK, ESWITCH_S, BREAK_S);
-        assertFail("compiler.err.break.missing.value", ESWITCH_S, BREAK_N);
-        assertFail("compiler.err.prob.found.req", ESWITCH_S, BREAK_Z);
-        assertFail("compiler.err.cant.resolve.location", ESWITCH_S, BREAK_L);
+        assertOK(ESWITCH_S, YIELD_S);
+        assertOK(LABEL, BLOCK, ESWITCH_S, YIELD_S);
+        assertFail("compiler.err.break.outside.switch.expression", ESWITCH_S, BREAK_N);
+        assertFail("compiler.err.prob.found.req", ESWITCH_S, YIELD_Z);
+        assertFail("compiler.err.undef.label", ESWITCH_S, BREAK_L);
         assertFail("compiler.err.break.outside.switch.expression", LABEL, BLOCK, ESWITCH_S, BREAK_L);
         assertFail("compiler.err.undef.label", ESWITCH_S, CONTINUE_L);
-        assertFail("compiler.err.cont.outside.loop", ESWITCH_S, CONTINUE_N);
+        assertFail("compiler.err.continue.outside.switch.expression", ESWITCH_S, CONTINUE_N);
         assertFail("compiler.err.return.outside.switch.expression", ESWITCH_S, RETURN_N);
         assertFail("compiler.err.return.outside.switch.expression", ESWITCH_S, RETURN_S);
         // Function-valued switch expression
-        assertOK(INT_FN_ESWITCH, BREAK_INT_FN);
-        assertFail("compiler.err.break.missing.value", INT_FN_ESWITCH, BREAK_N);
-        assertFail("compiler.err.prob.found.req", INT_FN_ESWITCH, BREAK_Z);
-        assertFail("compiler.err.prob.found.req", INT_FN_ESWITCH, BREAK_S);
+        assertOK(INT_FN_ESWITCH, YIELD_INT_FN);
+        assertFail("compiler.err.break.outside.switch.expression", INT_FN_ESWITCH, BREAK_N);
+        assertFail("compiler.err.prob.found.req", INT_FN_ESWITCH, YIELD_Z);
+        assertFail("compiler.err.prob.found.req", INT_FN_ESWITCH, YIELD_S);
 
-        assertFail("compiler.err.cant.resolve.location", INT_FN_ESWITCH, BREAK_L);
+        assertFail("compiler.err.undef.label", INT_FN_ESWITCH, BREAK_L);
         assertFail("compiler.err.break.outside.switch.expression", LABEL, BLOCK, INT_FN_ESWITCH, BREAK_L);
         assertFail("compiler.err.undef.label", INT_FN_ESWITCH, CONTINUE_L);
-        assertFail("compiler.err.cont.outside.loop", INT_FN_ESWITCH, CONTINUE_N);
+        assertFail("compiler.err.continue.outside.switch.expression", INT_FN_ESWITCH, CONTINUE_N);
         assertFail("compiler.err.return.outside.switch.expression", INT_FN_ESWITCH, RETURN_N);
         assertFail("compiler.err.return.outside.switch.expression", INT_FN_ESWITCH, RETURN_S);
 
     }
 
     public void testNestedInExpSwitch() {
-        assertOK(ESWITCH_Z, IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  BREAK_Z);
+        assertOK(ESWITCH_Z, IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  YIELD_Z);
         //
-        assertOK(ESWITCH_Z, IF,     IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, IF,     BLOCK,  BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  BREAK_Z);
+        assertOK(ESWITCH_Z, IF,     IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, IF,     BLOCK,  YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  YIELD_Z);
         //
-        assertOK(ESWITCH_Z, IF,     IF,     IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, IF,     IF,     BLOCK,  BREAK_Z);
-        assertOK(ESWITCH_Z, IF,     BLOCK,  IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, IF,     BLOCK,  BLOCK,  BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  IF,     IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  IF,     BLOCK,  BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  IF,     BREAK_Z);
-        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  BLOCK,  BREAK_Z);
+        assertOK(ESWITCH_Z, IF,     IF,     IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, IF,     IF,     BLOCK,  YIELD_Z);
+        assertOK(ESWITCH_Z, IF,     BLOCK,  IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, IF,     BLOCK,  BLOCK,  YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  IF,     IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  IF,     BLOCK,  YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  IF,     YIELD_Z);
+        assertOK(ESWITCH_Z, BLOCK,  BLOCK,  BLOCK,  YIELD_Z);
         //
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, SSWITCH, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, FOR, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, WHILE, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, DO, BREAK_Z);
-        assertFail("compiler.err.break.complex.value.no.switch.expression", ESWITCH_Z, INT_FN, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, SSWITCH, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, FOR, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, WHILE, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, DO, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, BLOCK, SSWITCH, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, BLOCK, FOR, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, BLOCK, WHILE, IF, BREAK_Z);
-        assertFail("compiler.err.break.expr.not.immediate", ESWITCH_Z, BLOCK, DO, IF, BREAK_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, SSWITCH, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, FOR, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, WHILE, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, DO, YIELD_Z);
+        assertFail("compiler.err.no.switch.expression", ESWITCH_Z, INT_FN, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, SSWITCH, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, FOR, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, WHILE, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, DO, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, BLOCK, SSWITCH, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, BLOCK, FOR, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, BLOCK, WHILE, IF, YIELD_Z);
+        assertOK(ESWITCH_Z, YIELD_Z, BLOCK, DO, IF, YIELD_Z);
     }
 
     public void testBreakExpressionLabelDisambiguation() {
-        assertOK(DEF_LABEL_VAR, ESWITCH_Z, BREAK_L);
-        assertFail("compiler.err.break.ambiguous.target", LABEL, FOR, BLOCK, DEF_LABEL_VAR, ESWITCH_Z, BREAK_L);
-        assertFail("compiler.err.break.ambiguous.target", DEF_LABEL_VAR, ESWITCH_Z, LABEL, FOR, BREAK_L); //label break
-        assertFail("compiler.err.break.ambiguous.target", DEF_LABEL_VAR, LABEL, BLOCK, ESWITCH_Z, BREAK_L); //expression break
+        assertOK(DEF_LABEL_VAR, ESWITCH_Z, YIELD_L);
+        assertFail("compiler.err.undef.label", DEF_LABEL_VAR, ESWITCH_Z, BREAK_L);
+        assertFail("compiler.err.break.outside.switch.expression", LABEL, FOR, BLOCK, DEF_LABEL_VAR, ESWITCH_Z, BREAK_L);
+        assertOK(DEF_LABEL_VAR, ESWITCH_Z, YIELD_Z, LABEL, FOR, BREAK_L); //label break
+        assertFail("compiler.err.break.outside.switch.expression", DEF_LABEL_VAR, LABEL, BLOCK, ESWITCH_Z, BREAK_L);
+        assertOK(DEF_LABEL_VAR, LABEL, BLOCK, ESWITCH_Z, YIELD_L); //expression break
         //
     }
 
     public void testFunReturningSwitchExp() {
-        assertOK(INT_FN_ESWITCH, BREAK_INT_FN);
+        assertOK(INT_FN_ESWITCH, YIELD_INT_FN);
     }
 
     public void testContinueLoops() {
--- a/test/langtools/tools/javac/lambda/deduplication/Deduplication.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lambda/deduplication/Deduplication.java	Wed Jun 12 10:02:49 2019 +0530
@@ -160,6 +160,9 @@
                 group((Consumer<Integer>) x -> Deduplication.this.f());
             }
         }
+
+        group((Function<Integer, Integer>) x -> switch (x) { default: yield x; },
+              (Function<Integer, Integer>) x -> switch (x) { default: yield x; });
     }
 
     void f() {}
--- a/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -84,6 +84,7 @@
         Listener diagnosticListener = new Listener();
         Path testSrc = Paths.get(System.getProperty("test.src"));
         Path file = testSrc.resolve("Deduplication.java");
+        String sourceVersion = Integer.toString(Runtime.version().feature());
         JavacTask task =
                 javacTool.getTask(
                         null,
@@ -93,7 +94,8 @@
                                 "-d",
                                 ".",
                                 "-XDdebug.dumpLambdaToMethodDeduplication",
-                                "-XDdebug.dumpLambdaToMethodStats"),
+                                "-XDdebug.dumpLambdaToMethodStats",
+                                "--enable-preview", "-source", sourceVersion),
                         null,
                         fileManager.getJavaFileObjects(file));
         Map<JCLambda, JCLambda> dedupedLambdas = new LinkedHashMap<>();
@@ -192,6 +194,9 @@
                             (JCLambda) d.getDiagnosticPosition().getTree(),
                             (MethodSymbol) d.getArgs()[0]);
                     break;
+                case "compiler.note.preview.filename":
+                case "compiler.note.preview.recompile":
+                    break; //ignore
                 default:
                     unexpected.add(diagnostic);
             }
--- a/test/langtools/tools/javac/lib/DPrinter.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lib/DPrinter.java	Wed Jun 12 10:02:49 2019 +0530
@@ -782,6 +782,11 @@
 
         @Override
         public void visitBreak(JCBreak tree) {
+            printName("label", tree.label);
+        }
+
+        @Override
+        public void visitYield(JCYield tree) {
             printTree("value", tree.value);
         }
 
--- a/test/langtools/tools/javac/lvti/ParserTest.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lvti/ParserTest.out	Wed Jun 12 10:02:49 2019 +0530
@@ -1,24 +1,24 @@
-ParserTest.java:14:18: compiler.err.var.not.allowed
-ParserTest.java:16:22: compiler.err.var.not.allowed
-ParserTest.java:20:19: compiler.err.var.not.allowed
-ParserTest.java:24:14: compiler.err.var.not.allowed
-ParserTest.java:28:20: compiler.err.var.not.allowed
-ParserTest.java:36:27: compiler.err.var.not.allowed
-ParserTest.java:38:5: compiler.err.var.not.allowed.here
-ParserTest.java:41:15: compiler.err.var.not.allowed.array
-ParserTest.java:42:13: compiler.err.var.not.allowed.array
-ParserTest.java:43:17: compiler.err.var.not.allowed.array
-ParserTest.java:44:13: compiler.err.var.not.allowed.array
-ParserTest.java:45:15: compiler.err.var.not.allowed.array
-ParserTest.java:46:13: compiler.err.var.not.allowed.array
-ParserTest.java:49:24: compiler.err.var.not.allowed.compound
-ParserTest.java:54:5: compiler.err.var.not.allowed.here
-ParserTest.java:58:16: compiler.err.var.not.allowed.here
-ParserTest.java:59:14: compiler.err.var.not.allowed.here
-ParserTest.java:60:24: compiler.err.var.not.allowed.here
-ParserTest.java:61:22: compiler.err.var.not.allowed.here
-ParserTest.java:63:22: compiler.err.var.not.allowed.here
-ParserTest.java:64:18: compiler.err.var.not.allowed.here
-ParserTest.java:68:35: compiler.err.var.not.allowed.here
-ParserTest.java:69:22: compiler.err.var.not.allowed.here
+ParserTest.java:14:18: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:16:22: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:20:19: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:24:14: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:28:20: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:36:27: compiler.err.restricted.type.not.allowed: var, 10
+ParserTest.java:38:5: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:41:15: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:42:13: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:43:17: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:44:13: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:45:15: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:46:13: compiler.err.restricted.type.not.allowed.array: var
+ParserTest.java:49:24: compiler.err.restricted.type.not.allowed.compound: var
+ParserTest.java:54:5: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:58:16: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:59:14: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:60:24: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:61:22: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:63:22: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:64:18: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:68:35: compiler.err.restricted.type.not.allowed.here: var
+ParserTest.java:69:22: compiler.err.restricted.type.not.allowed.here: var
 23 errors
--- a/test/langtools/tools/javac/lvti/ParserTest9.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lvti/ParserTest9.out	Wed Jun 12 10:02:49 2019 +0530
@@ -1,31 +1,31 @@
-ParserTest.java:14:18: compiler.warn.var.not.allowed
-ParserTest.java:16:22: compiler.warn.var.not.allowed
-ParserTest.java:20:19: compiler.warn.var.not.allowed
-ParserTest.java:24:14: compiler.warn.var.not.allowed
-ParserTest.java:28:20: compiler.warn.var.not.allowed
-ParserTest.java:36:27: compiler.warn.var.not.allowed
-ParserTest.java:38:5: compiler.warn.var.not.allowed
-ParserTest.java:41:15: compiler.warn.var.not.allowed
-ParserTest.java:42:13: compiler.warn.var.not.allowed
-ParserTest.java:43:17: compiler.warn.var.not.allowed
-ParserTest.java:44:13: compiler.warn.var.not.allowed
-ParserTest.java:45:15: compiler.warn.var.not.allowed
-ParserTest.java:46:13: compiler.warn.var.not.allowed
-ParserTest.java:47:23: compiler.warn.var.not.allowed
-ParserTest.java:48:13: compiler.warn.var.not.allowed
-ParserTest.java:49:13: compiler.warn.var.not.allowed
-ParserTest.java:50:23: compiler.warn.var.not.allowed
-ParserTest.java:51:23: compiler.warn.var.not.allowed
-ParserTest.java:54:5: compiler.warn.var.not.allowed
-ParserTest.java:58:16: compiler.warn.var.not.allowed
-ParserTest.java:59:14: compiler.warn.var.not.allowed
-ParserTest.java:60:24: compiler.warn.var.not.allowed
-ParserTest.java:61:22: compiler.warn.var.not.allowed
-ParserTest.java:63:22: compiler.warn.var.not.allowed
-ParserTest.java:63:40: compiler.warn.var.not.allowed
-ParserTest.java:64:18: compiler.warn.var.not.allowed
-ParserTest.java:68:35: compiler.warn.var.not.allowed
-ParserTest.java:69:22: compiler.warn.var.not.allowed
-ParserTest.java:73:24: compiler.warn.var.not.allowed
-ParserTest.java:74:18: compiler.warn.var.not.allowed
-30 warnings
+ParserTest.java:14:18: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:16:22: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:20:19: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:24:14: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:28:20: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:36:27: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:38:5: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:41:15: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:42:13: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:43:17: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:44:13: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:45:15: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:46:13: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:47:23: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:48:13: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:49:13: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:50:23: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:51:23: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:54:5: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:58:16: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:59:14: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:60:24: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:61:22: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:63:22: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:63:40: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:64:18: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:68:35: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:69:22: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:73:24: compiler.warn.restricted.type.not.allowed: var, 10
+ParserTest.java:74:18: compiler.warn.restricted.type.not.allowed: var, 10
+30 warnings
\ No newline at end of file
--- a/test/langtools/tools/javac/lvti/badTypeReference/BadTypeReference.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/lvti/badTypeReference/BadTypeReference.out	Wed Jun 12 10:02:49 2019 +0530
@@ -1,3 +1,3 @@
-BadTypeReference.java:14:9: compiler.err.illegal.ref.to.var.type
-BadTypeReference.java:15:21: compiler.err.illegal.ref.to.var.type
+BadTypeReference.java:14:9: compiler.err.illegal.ref.to.restricted.type: var
+BadTypeReference.java:15:21: compiler.err.illegal.ref.to.restricted.type: var
 2 errors
--- a/test/langtools/tools/javac/parser/JavacParserTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/parser/JavacParserTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1083,12 +1083,12 @@
                       "        }" +
                       "        int j = switch (i) {" +
                       "            case 0 -> i + 1;" +
-                      "            case 1 -> { break i + 1; }" +
+                      "            case 1 -> { yield i + 1; }" +
                       "            default -> throw new RuntimeException();" +
                       "        };" +
                       "        int k = switch (i) {" +
-                      "            case 0: break i + 1;" +
-                      "            case 1: { break i + 1; }" +
+                      "            case 0: yield i + 1;" +
+                      "            case 1: { yield i + 1; }" +
                       "            default: throw new RuntimeException();" +
                       "        };" +
                       "    }" +
@@ -1120,7 +1120,7 @@
         List<String> expectedSpans = List.of(
                 "i++;", "{ i++; }", "throw new RuntimeException();", "if (true) ;", "i++;",
                 "<null>", "<null>", "<null>", "<null>", "<null>",
-                "i + 1"/*TODO semicolon?*/, "{ break i + 1; }", "throw new RuntimeException();",
+                "i + 1"/*TODO semicolon?*/, "{ yield i + 1; }", "throw new RuntimeException();",
                 "<null>", "<null>", "<null>");
         assertEquals("the error spans are not correct; actual:" + spans, expectedSpans, spans);
         String toString = normalize(cut.toString());
@@ -1162,19 +1162,19 @@
                 "        \n" +
                 "        }\n" +
                 "        int j = switch (i) {\n" +
-                "        case 0 -> break i + 1;\n" +
+                "        case 0 -> yield i + 1;\n" +
                 "        case 1 -> {\n" +
-                "            break i + 1;\n" +
+                "            yield i + 1;\n" +
                 "        }\n" +
                 "        default -> throw new RuntimeException();\n" +
                 "        };\n" +
                 "        int k = switch (i) {\n" +
                 "        case 0:\n" +
-                "            break i + 1;\n" +
+                "            yield i + 1;\n" +
                 "        \n" +
                 "        case 1:\n" +
                 "            {\n" +
-                "                break i + 1;\n" +
+                "                yield i + 1;\n" +
                 "            }\n" +
                 "        \n" +
                 "        default:\n" +
--- a/test/langtools/tools/javac/switchexpr/BreakTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/BreakTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -54,7 +54,7 @@
             "    int t2(Integer i) {" +
             "        return switch (i) {" +
             "            case null: break LABEL;" +
-            "            default: break 2;" +
+            "            default: yield 2;" +
             "        }" +
             "    }" +
             "}";
@@ -79,7 +79,7 @@
             }
         }.scan(ct.parse(), null);
 
-        List<String> expected = Arrays.asList("LABEL", null, "LABEL", null);
+        List<String> expected = Arrays.asList("LABEL", null, "LABEL");
 
         if (!expected.equals(labels)) {
             throw new AssertionError("Unexpected labels found: " + labels);
--- a/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java	Wed Jun 12 10:02:49 2019 +0530
@@ -37,8 +37,8 @@
         int x;
 
         boolean t1 = (b && switch(a) {
-            case 0: break (x = 1) == 1 || true;
-            default: break false;
+            case 0: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t1) {
@@ -50,8 +50,8 @@
         int x;
 
         boolean t1 = (b && switch(a) {
-            case 0: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case 0: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t1) {
@@ -63,8 +63,8 @@
         int x;
 
         boolean t1a = (b && switch(a) {
-            case 0: break (x = 1) == 1;
-            default: break false;
+            case 0: yield (x = 1) == 1;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t1a) {
@@ -76,8 +76,8 @@
         int x;
 
         boolean t1b = (switch(a) {
-            case 0: break (x = 1) == 1;
-            default: break false;
+            case 0: yield (x = 1) == 1;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t1b) {
@@ -89,8 +89,8 @@
         int x;
 
         boolean t2 = !(b && switch(a) {
-            case 0: break (x = 1) == 1 || true;
-            default: break false;
+            case 0: yield (x = 1) == 1 || true;
+            default: yield false;
         }) || x == 1;
 
         if (!t2) {
@@ -102,8 +102,8 @@
         int x;
 
         boolean t2 = !(b && switch(a) {
-            case 0: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case 0: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) || x == 1;
 
         if (!t2) {
@@ -115,8 +115,8 @@
         int x;
 
         boolean t3 = !(switch(a) {
-            case 0: break (x = 1) == 1 || true;
-            default: break false;
+            case 0: yield (x = 1) == 1 || true;
+            default: yield false;
         }) || x == 2;
 
         if (t3) {
@@ -128,8 +128,8 @@
         int x;
 
         boolean t3 = !(switch(a) {
-            case 0: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case 0: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) || x == 2;
 
         if (t3) {
@@ -141,7 +141,7 @@
         int x;
 
         boolean t4 = (b && switch(a) {
-            case 0: break (x = 1) == 1 || true;
+            case 0: yield (x = 1) == 1 || true;
             default: throw new IllegalStateException();
         }) && x == 1; //x is definitelly assigned here
 
@@ -155,7 +155,7 @@
         int x;
 
         boolean t4 = (b && switch(a) {
-            case 0: break (x = 1) == 1 || isTrue();
+            case 0: yield (x = 1) == 1 || isTrue();
             default: throw new IllegalStateException();
         }) && x == 1; //x is definitelly assigned here
 
@@ -170,8 +170,8 @@
         String s = "a";
 
         boolean t5 = (switch(s) {
-            case "a": break (x = 1) == 1 || true;
-            default: break false;
+            case "a": yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t5) {
@@ -185,8 +185,8 @@
         String s = "a";
 
         boolean t5 = (switch(s) {
-            case "a": break (x = 1) == 1 || isTrue();
-            default: break false;
+            case "a": yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t5) {
@@ -199,8 +199,8 @@
         E e = E.B;
 
         boolean t6 = (switch(e) {
-            case B: break (x = 1) == 1 || true;
-            default: break false;
+            case B: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t6) {
@@ -213,8 +213,8 @@
         E e = E.B;
 
         boolean t6 = (switch(e) {
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t6) {
@@ -251,9 +251,9 @@
         E e = E.B;
 
         boolean t8 = (switch(e) {
-            case A: x = 1; break true;
-            case B: break (x = 1) == 1 || true;
-            default: break false;
+            case A: x = 1; yield true;
+            case B: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t8) {
@@ -266,9 +266,9 @@
         E e = E.B;
 
         boolean t8 = (switch(e) {
-            case A: x = 1; break isTrue();
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case A: x = 1; yield isTrue();
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t8) {
@@ -281,9 +281,9 @@
         E e = E.A;
 
         boolean t9 = (switch(e) {
-            case A: x = 1; break true;
-            case B: break (x = 1) == 1 || true;
-            default: break false;
+            case A: x = 1; yield true;
+            case B: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t9) {
@@ -296,9 +296,9 @@
         E e = E.A;
 
         boolean t9 = (switch(e) {
-            case A: x = 1; break isTrue();
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case A: x = 1; yield isTrue();
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!t9) {
@@ -311,9 +311,9 @@
         E e = E.C;
 
         boolean tA = (switch(e) {
-            case A: x = 1; break true;
-            case B: break (x = 1) == 1 || true;
-            default: break false;
+            case A: x = 1; yield true;
+            case B: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (tA) {
@@ -326,9 +326,9 @@
         E e = E.C;
 
         boolean tA = (switch(e) {
-            case A: x = 1; break isTrue();
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case A: x = 1; yield isTrue();
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (tA) {
@@ -341,9 +341,9 @@
         E e = E.C;
 
         boolean tA = (switch(e) {
-            case A: x = 1; break true;
-            case B: break (x = 2) == 2 || true;
-            default: break false;
+            case A: x = 1; yield true;
+            case B: yield (x = 2) == 2 || true;
+            default: yield false;
         }) || (x = 3) == 3; //x is definitelly unassigned here
 
         if (x != 3) {
@@ -356,9 +356,9 @@
         E e = E.A;
 
         boolean tA = (switch(e) {
-            case A: break isTrue() && (x = 1) == 1;
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case A: yield isTrue() && (x = 1) == 1;
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!tA) {
@@ -371,9 +371,9 @@
         E e = E.A;
 
         boolean tA = (switch(e) {
-            case A: break isTrue() && e != E.C ? (x = 1) == 1 && e != E.B : false;
-            case B: break (x = 1) == 1 || true;
-            default: break false;
+            case A: yield isTrue() && e != E.C ? (x = 1) == 1 && e != E.B : false;
+            case B: yield (x = 1) == 1 || true;
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!tA) {
@@ -386,9 +386,9 @@
         E e = E.A;
 
         boolean tA = (switch(e) {
-            case A: break isTrue() && e != E.C ? (x = 1) == 1 && e != E.B : false;
-            case B: break (x = 1) == 1 || isTrue();
-            default: break false;
+            case A: yield isTrue() && e != E.C ? (x = 1) == 1 && e != E.B : false;
+            case B: yield (x = 1) == 1 || isTrue();
+            default: yield false;
         }) && x == 1; //x is definitelly assigned here
 
         if (!tA) {
@@ -416,9 +416,9 @@
         E e = E.A;
 
         boolean tA = (switch(e) {
-            case A -> { x = 1; break true; }
-            case B -> { x = 1; break true; }
-            case C -> { x = 1; break true; }
+            case A -> { x = 1; yield true; }
+            case B -> { x = 1; yield true; }
+            case C -> { x = 1; yield true; }
         }) && x == 1; //x is definitelly assigned here
 
         if (!tA) {
--- a/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -15,8 +15,8 @@
             int x;
 
             t = (b && switch(a) {
-                case 0: break (x = 1) == 1 || true;
-                default: break false;
+                case 0: yield (x = 1) == 1 || true;
+                default: yield false;
             }) || x == 1;
         }
 
@@ -24,8 +24,8 @@
             int x;
 
             t = (switch(a) {
-                case 0: break (x = 1) == 1;
-                default: break false;
+                case 0: yield (x = 1) == 1;
+                default: yield false;
             }) || x == 1;
         }
 
@@ -33,9 +33,9 @@
             int x;
 
             t = (switch(a) {
-                case 0: x = 1; break true;
-                case 1: break (x = 1) == 1;
-                default: break false;
+                case 0: x = 1; yield true;
+                case 1: yield (x = 1) == 1;
+                default: yield false;
             }) || x == 1;
         }
 
@@ -43,9 +43,9 @@
             int x;
 
             t = (switch(a) {
-                case 0: break true;
-                case 1: break (x = 1) == 1;
-                default: break false;
+                case 0: yield true;
+                case 1: yield (x = 1) == 1;
+                default: yield false;
             }) && x == 1;
         }
 
@@ -53,9 +53,9 @@
             int x;
 
             t = (switch(a) {
-                case 0: break false;
-                case 1: break isTrue() || (x = 1) == 1;
-                default: break false;
+                case 0: yield false;
+                case 1: yield isTrue() || (x = 1) == 1;
+                default: yield false;
             }) && x == 1;
         }
 
@@ -63,9 +63,9 @@
             int x;
 
             t = (switch(a) {
-                case 0: break false;
-                case 1: break isTrue() ? true : (x = 1) == 1;
-                default: break false;
+                case 0: yield false;
+                case 1: yield isTrue() ? true : (x = 1) == 1;
+                default: yield false;
             }) && x == 1;
         }
 
@@ -73,9 +73,9 @@
             final int x;
 
             t = (switch(a) {
-                case 0: break false;
-                case 1: break isTrue() ? true : (x = 1) == 1;
-                default: break false;
+                case 0: yield false;
+                case 1: yield isTrue() ? true : (x = 1) == 1;
+                default: yield false;
             }) && (x = 1) == 1;
         }
     }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java	Wed Jun 12 10:02:49 2019 +0530
@@ -39,15 +39,15 @@
     private String print(T t) {
         return switch (t) {
             case A -> "A";
-            case B -> { break "B"; }
-            default -> { break "other"; }
+            case B -> { yield "B"; }
+            default -> { yield "other"; }
         };
     }
 
     private String exhaustive1(T t) {
         return switch (t) {
             case A -> "A";
-            case B -> { break "B"; }
+            case B -> { yield "B"; }
             case C -> "C";
             case D -> "D";
         };
@@ -64,25 +64,25 @@
 
     private String scopesIsolated(T t) {
         return switch (t) {
-            case A -> { String res = "A"; break res;}
-            case B -> { String res = "B"; break res;}
-            default -> { String res = "default"; break res;}
+            case A -> { String res = "A"; yield res;}
+            case B -> { String res = "B"; yield res;}
+            default -> { String res = "default"; yield res;}
         };
     }
 
     private Supplier<String> lambdas1(T t) {
         return switch (t) {
             case A -> () -> "A";
-            case B -> { break () -> "B"; }
+            case B -> { yield () -> "B"; }
             default -> () -> "default";
         };
     }
 
     private Supplier<String> lambdas2(T t) {
         return switch (t) {
-            case A: break () -> "A";
-            case B: { break () -> "B"; }
-            default: break () -> "default";
+            case A: yield () -> "A";
+            case B: { yield () -> "B"; }
+            default: yield () -> "default";
         };
     }
 
@@ -91,16 +91,16 @@
                 ? -2
                 : switch (s) {
                       case "A", "B" -> 0;
-                      case "C" -> { break 1; }
+                      case "C" -> { yield 1; }
                       default -> -1;
                   };
     }
 
     private int convert2(String s) {
         return switch (s) {
-            case "A", "B": break 0;
-            case "C": break 1;
-            default: break -1;
+            case "A", "B": yield 0;
+            case "C": yield 1;
+            default: yield -1;
         };
     }
 
@@ -112,7 +112,7 @@
                     default: break STOP;
                 }
                 return switch (t) {
-                    default: break good;
+                    default: yield good;
                 };
             }
         }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java	Wed Jun 12 10:02:49 2019 +0530
@@ -58,11 +58,11 @@
             case 0:
                 return switch (j) {
                     case 0:
-                        if (true) break "0-0";
+                        if (true) yield "0-0";
                     case 1:
-                        break "0-1";
+                        yield "0-1";
                     default:
-                        break "0-X";
+                        yield "0-X";
                 };
             default: return "X";
         }
@@ -90,9 +90,9 @@
                         r = "0-X";
                         break;
                 }
-                break r;
+                yield r;
             case 1:
-                break "1";
+                yield "1";
             case 2:
                 LOP: while (j-- > 0) {
                     if (k == 5) {
@@ -102,9 +102,9 @@
                     break LOP;
                 }
                 Supplier<String> getter = () -> { return "2-X-5"; };
-                break getter.get();
+                yield getter.get();
             default:
-                break "X";
+                yield "X";
         };
     }
 
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -12,7 +12,7 @@
             case 0:
                 return switch (j) {
                     case 0:
-                        break "0-0";
+                        yield "0-0";
                     case 1:
                         break ; //error: missing value
                     case 2:
@@ -20,9 +20,9 @@
                     case 3: {
                         int x = -1;
                         x: switch (i + j) {
-                            case 0: break x; //error: cannot disambiguate, wrong type as well
+                            case 0: break x;
                         }
-                        break "X";
+                        yield "X";
                     }
                     case 4: return "X"; //error: no returns from inside of the switch expression
                     case 5: continue;   //error: no continue out of the switch expression
@@ -31,17 +31,17 @@
                     default: {
                         String x = "X";
                         x: switch (i + j) {
-                            case 0: break ""; //error: cannot break from switch expression that is not immediatelly enclosing
+                            case 0: yield ""; //error: cannot yield from switch expression that is not immediatelly enclosing
                         }
-                        break "X";
+                        yield "X";
                     }
                 };
             case 1:
-                break "1" + undef; //error: complex value and no switch expression
+                yield "1" + undef; //error: complex value and no switch expression
         }
         }
         j: print(switch (i) {
-            default: break j; //error: "j" is ambiguous (expression/label)
+            default: break j;
         }, 0);
         j2: print(switch (i) {
             default: break j2;
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.out	Wed Jun 12 10:02:49 2019 +0530
@@ -1,15 +1,12 @@
-ExpressionSwitchBreaks2.java:17:25: compiler.err.break.missing.value
 ExpressionSwitchBreaks2.java:19:25: compiler.err.break.outside.switch.expression
-ExpressionSwitchBreaks2.java:23:37: compiler.err.break.ambiguous.target: x
 ExpressionSwitchBreaks2.java:27:29: compiler.err.return.outside.switch.expression
 ExpressionSwitchBreaks2.java:28:29: compiler.err.continue.outside.switch.expression
 ExpressionSwitchBreaks2.java:29:29: compiler.err.continue.outside.switch.expression
 ExpressionSwitchBreaks2.java:30:29: compiler.err.undef.label: UNKNOWN
-ExpressionSwitchBreaks2.java:34:37: compiler.err.break.expr.not.immediate: compiler.misc.tree.tag.switch
-ExpressionSwitchBreaks2.java:40:17: compiler.err.break.complex.value.no.switch.expression
+ExpressionSwitchBreaks2.java:40:17: compiler.err.no.switch.expression
 ExpressionSwitchBreaks2.java:40:29: compiler.err.cant.resolve.location: kindname.variable, undef, , , (compiler.misc.location: kindname.class, ExpressionSwitchBreaks2, null)
-ExpressionSwitchBreaks2.java:44:22: compiler.err.break.ambiguous.target: j
+ExpressionSwitchBreaks2.java:44:22: compiler.err.break.outside.switch.expression
 ExpressionSwitchBreaks2.java:47:22: compiler.err.break.outside.switch.expression
 - compiler.note.preview.filename: ExpressionSwitchBreaks2.java
 - compiler.note.preview.recompile
-12 errors
+9 errors
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java	Wed Jun 12 10:02:49 2019 +0530
@@ -34,47 +34,49 @@
         new ExpressionSwitchBugs().testNested();
         new ExpressionSwitchBugs().testAnonymousClasses();
         new ExpressionSwitchBugs().testFields();
+        check(3, new C(-1, 3).test(false));
+        check(3, new C(3, -1).test(true));
     }
 
     private void testNested() {
         int i = 0;
         check(42, id(switch (42) {
-            default: i++; break 42;
+            default: i++; yield 42;
         }));
         i = 0;
         check(43, id(switch (42) {
             case 42: while (i == 0) {
                 i++;
             }
-            break 42 + i;
-            default: i++; break 42;
+            yield 42 + i;
+            default: i++; yield 42;
         }));
         i = 0;
         check(42, id(switch (42) {
             case 42: if (i == 0) {
-                break 42;
+                yield 42;
             }
-            default: i++; break 43;
+            default: i++; yield 43;
         }));
         i = 0;
         check(42, id(switch (42) {
             case 42: if (i == 0) {
-                break 41 + switch (0) {
+                yield 41 + switch (0) {
                     case 0 -> 1;
                     default -> -1;
                 };
             }
-            default: i++; break 43;
+            default: i++; yield 43;
         }));
     }
 
     private void testAnonymousClasses() {
         for (int i : new int[] {1, 2}) {
             check(3, id((switch (i) {
-                case 1: break new I() {
+                case 1: yield new I() {
                     public int g() { return 3; }
                 };
-                default: break (I) () -> { return 3; };
+                default: yield (I) () -> { return 3; };
             }).g()));
             check(3, id((switch (i) {
                 case 1 -> new I() {
@@ -96,7 +98,7 @@
         case 2 -> {
             int temp = 0;
             temp += 3;
-            break temp;
+            yield temp;
         }
         default -> throw new IllegalStateException();
     });
@@ -107,7 +109,7 @@
         case 2 -> {
             int temp = 0;
             temp += 3;
-            break temp;
+            yield temp;
         }
         default -> throw new IllegalStateException();
     });
@@ -120,7 +122,7 @@
         return -1;
     }
 
-    private void check(int actual, int expected) {
+    private static void check(int actual, int expected) {
         if (actual != expected) {
             throw new AssertionError("Unexpected result: " + actual);
         }
@@ -129,4 +131,32 @@
     public interface I {
         public int g();
     }
+
+    static class Super {
+        public final int i;
+
+        public Super(int i) {
+            this.i = i;
+        }
+
+    }
+    static class C extends Super {
+        public final int i;
+
+        public C(int superI, int i) {
+            super(superI);
+            this.i = i;
+        }
+
+        public int test(boolean fromSuper) {
+            return switch (fromSuper ? 0 : 1) {
+                case 0 -> {
+                    yield super.i;
+                }
+                default -> {
+                    yield this.i;
+                }
+            };
+        }
+    }
 }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java	Wed Jun 12 10:02:49 2019 +0530
@@ -70,7 +70,7 @@
         int i;
         int j = 0;
         int k = switch (j) {
-            case 0  -> { i=42; break 42; }
+            case 0  -> { i=42; yield 42; }
             default -> i=42;
         };
         System.out.println(i);
@@ -80,7 +80,7 @@
         int j = 0;
         int k = switch (j) {
             case 0  -> i=42;
-            default -> { i=42; break 42; }
+            default -> { i=42; yield 42; }
         };
         System.out.println(i);
     }
@@ -88,8 +88,8 @@
         int i;
         int j = 0;
         int k = switch (j) {
-            case 0  -> { i=42; break 42; }
-            default -> { i=42; break 42; }
+            case 0  -> { i=42; yield 42; }
+            default -> { i=42; yield 42; }
         };
         System.out.println(i);
     }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java	Wed Jun 12 10:02:49 2019 +0530
@@ -39,19 +39,19 @@
             int i = 6;
             int o = 0;
             while (switch (i) {
-                case 1: i = 0; break true;
-                case 2: i = 1; break true;
+                case 1: i = 0; yield true;
+                case 2: i = 1; yield true;
                 case 3, 4: i--;
                     if (i == 2 || i == 4) {
-                        break switch (i) {
+                        yield switch (i) {
                             case 2 -> true;
                             case 4 -> false;
                             default -> throw new IllegalStateException();
                         };
                     } else {
-                        break true;
+                        yield true;
                     }
-                default: i--; break switch (i) {
+                default: i--; yield switch (i) {
                     case -1 -> false;
                     case 3 -> true;
                     default -> true;
@@ -67,8 +67,8 @@
             int i = 6;
             int o = 0;
             while (switch (i) {
-                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; break true; }
-                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; break true; }
+                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; yield true; }
+                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; yield true; }
                 case 3, 4:
                     try {
                         new ExpressionSwitchEmbedding().throwException();
@@ -76,16 +76,16 @@
                         i--;
                         if (i == 2 || i == 4) {
                             try {
-                                break switch (i) {
+                                yield switch (i) {
                                     case 2 -> throw new ResultException(true);
                                     case 4 -> false;
                                     default -> throw new IllegalStateException();
                                 };
                             } catch (ResultException ex) {
-                                break ex.result;
+                                yield ex.result;
                             }
                         } else {
-                            break true;
+                            yield true;
                         }
                     }
                 default:
@@ -93,7 +93,7 @@
                         new ExpressionSwitchEmbedding().throwException();
                     } catch (Throwable t) {
                         i--;
-                        break switch (i) {
+                        yield switch (i) {
                             case -1 -> false;
                             case 3 -> true;
                             default -> true;
@@ -111,19 +111,19 @@
             int i = 6;
             int o = 0;
             if (switch (i) {
-                case 1: i = 0; break true;
-                case 2: i = 1; break true;
+                case 1: i = 0; yield true;
+                case 2: i = 1; yield true;
                 case 3, 4: i--;
                     if (i == 2 || i == 4) {
-                        break (switch (i) {
+                        yield (switch (i) {
                             case 2 -> 3;
                             case 4 -> 5;
                             default -> throw new IllegalStateException();
                         }) == i + 1;
                     } else {
-                        break true;
+                        yield true;
                     }
-                default: i--; break switch (i) {
+                default: i--; yield switch (i) {
                     case -1 -> false;
                     case 3 -> true;
                     default -> true;
@@ -139,8 +139,8 @@
             int i = 6;
             int o = 0;
             if (switch (i) {
-                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; break true; }
-                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; break true; }
+                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; yield true; }
+                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; yield true; }
                 case 3, 4:
                     try {
                         new ExpressionSwitchEmbedding().throwException();
@@ -148,16 +148,16 @@
                         i--;
                         if (i == 2 || i == 4) {
                             try {
-                                break switch (i) {
+                                yield switch (i) {
                                     case 2 -> throw new ResultException(true);
                                     case 4 -> false;
                                     default -> throw new IllegalStateException();
                                 };
                             } catch (ResultException ex) {
-                                break ex.result;
+                                yield ex.result;
                             }
                         } else {
-                            break true;
+                            yield true;
                         }
                     }
                 default:
@@ -165,7 +165,7 @@
                         new ExpressionSwitchEmbedding().throwException();
                     } catch (Throwable t) {
                         i--;
-                        break switch (i) {
+                        yield switch (i) {
                             case -1 -> false;
                             case 3 -> true;
                             default -> true;
@@ -182,19 +182,19 @@
         {
             int o = 0;
             for (int i = 6; (switch (i) {
-                case 1: i = 0; break true;
-                case 2: i = 1; break true;
+                case 1: i = 0; yield true;
+                case 2: i = 1; yield true;
                 case 3, 4: i--;
                     if (i == 2 || i == 4) {
-                        break switch (i) {
+                        yield switch (i) {
                             case 2 -> true;
                             case 4 -> false;
                             default -> throw new IllegalStateException();
                         };
                     } else {
-                        break true;
+                        yield true;
                     }
-                default: i--; break switch (i) {
+                default: i--; yield switch (i) {
                     case -1 -> false;
                     case 3 -> true;
                     default -> true;
@@ -209,8 +209,8 @@
         {
             int o = 0;
             for (int i = 6; (switch (i) {
-                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; break true; }
-                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; break true; }
+                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; yield true; }
+                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; yield true; }
                 case 3, 4:
                     try {
                         new ExpressionSwitchEmbedding().throwException();
@@ -218,16 +218,16 @@
                         i--;
                         if (i == 2 || i == 4) {
                             try {
-                                break switch (i) {
+                                yield switch (i) {
                                     case 2 -> throw new ResultException(true);
                                     case 4 -> false;
                                     default -> throw new IllegalStateException();
                                 };
                             } catch (ResultException ex) {
-                                break ex.result;
+                                yield ex.result;
                             }
                         } else {
-                            break true;
+                            yield true;
                         }
                     }
                 default:
@@ -235,7 +235,7 @@
                         new ExpressionSwitchEmbedding().throwException();
                     } catch (Throwable t) {
                         i--;
-                        break switch (i) {
+                        yield switch (i) {
                             case -1 -> false;
                             case 3 -> true;
                             default -> true;
@@ -255,19 +255,19 @@
             do {
                 o++;
             } while (switch (i) {
-                case 1: i = 0; break true;
-                case 2: i = 1; break true;
+                case 1: i = 0; yield true;
+                case 2: i = 1; yield true;
                 case 3, 4: i--;
                     if (i == 2 || i == 4) {
-                        break switch (i) {
+                        yield switch (i) {
                             case 2 -> true;
                             case 4 -> false;
                             default -> throw new IllegalStateException();
                         };
                     } else {
-                        break true;
+                        yield true;
                     }
-                default: i--; break switch (i) {
+                default: i--; yield switch (i) {
                     case -1 -> false;
                     case 3 -> true;
                     default -> true;
@@ -283,8 +283,8 @@
             do {
                 o++;
             } while (switch (i) {
-                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; break true; }
-                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; break true; }
+                case 1: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 0; yield true; }
+                case 2: try { new ExpressionSwitchEmbedding().throwException(); } catch (Throwable t) { i = 1; yield true; }
                 case 3, 4:
                     try {
                         new ExpressionSwitchEmbedding().throwException();
@@ -292,16 +292,16 @@
                         i--;
                         if (i == 2 || i == 4) {
                             try {
-                                break switch (i) {
+                                yield switch (i) {
                                     case 2 -> throw new ResultException(true);
                                     case 4 -> false;
                                     default -> throw new IllegalStateException();
                                 };
                             } catch (ResultException ex) {
-                                break ex.result;
+                                yield ex.result;
                             }
                         } else {
-                            break true;
+                            yield true;
                         }
                     }
                 default:
@@ -309,7 +309,7 @@
                         new ExpressionSwitchEmbedding().throwException();
                     } catch (Throwable t) {
                         i--;
-                        break switch (i) {
+                        yield switch (i) {
                             case -1 -> false;
                             case 3 -> true;
                             default -> true;
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java	Wed Jun 12 10:02:49 2019 +0530
@@ -53,7 +53,7 @@
         return switch (t) {
             case A: help = "a";
             case B: help += "b";
-            default: break help;
+            default: yield help;
         };
     }
 
@@ -62,7 +62,7 @@
         return switch (t) {
             case A: help = "a";
             case B: help += "b";
-            default: break help;
+            default: yield help;
         };
     }
 
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java	Wed Jun 12 10:02:49 2019 +0530
@@ -50,8 +50,8 @@
         return switch (p) {
             case 0: result += "0";
             case 1: result += "1";
-                break result;
-            default: break "other";
+                yield result;
+            default: yield "other";
         };
     }
 
@@ -60,7 +60,7 @@
         switch (p) {
             case 0: result += "0";
             case 1: result += "1";
-                break ;
+                break;
             default: result = "other";
                 break;
         }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java	Wed Jun 12 10:02:49 2019 +0530
@@ -9,7 +9,7 @@
     private String test1(int i) {
         return switch (i) {
             case 0 -> {}
-            default -> { break "other"; }
+            default -> { yield "other"; }
         };
     }
     private String test2(int i) {
@@ -27,7 +27,7 @@
     }
     private String test4(int i) {
         return switch (i) {
-            case 0 -> { break "other"; }
+            case 0 -> { yield "other"; }
             default -> {}
         };
     }
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java	Wed Jun 12 10:02:49 2019 +0530
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,11 +43,11 @@
             default -> {
                 int k = switch (j) {
                     default -> {
-                        break 42;
+                        yield 42;
                     }
                 };
-                System.out.println("didn't break to the top level");
-                break 43;
+                System.out.println("didn't yield to the top level");
+                yield 43;
             }
         };
         if (i!=43) {
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java	Wed Jun 12 10:02:49 2019 +0530
@@ -27,7 +27,7 @@
 
         String str = switch (param) {
             case "" -> {
-                break 0;
+                yield 0;
             } default ->"default";
         };
 
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java	Wed Jun 12 10:02:49 2019 +0530
@@ -26,9 +26,9 @@
                         s = "42";
                         break;
                 }
-                break s;
+                yield s;
             default:
-                break "43";
+                yield "43";
         };
     }
     enum E {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchToString.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8223305
+ * @summary Verify Tree.toString() related to switch expressions
+ * @modules jdk.compiler
+ */
+
+import java.net.URI;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.tools.*;
+
+import com.sun.source.util.JavacTask;
+
+public class ExpressionSwitchToString {
+
+    private static final String CODE =
+            "public class C {" +
+            "    void t1(Integer i) {" +
+            "        switch (i) {" +
+            "            case null: i++; break;" +
+            "            case 0, 1: i++; break;" +
+            "            default: i++; break;" +
+            "        }" +
+            "    }" +
+            "    int t2(Integer i) {" +
+            "        return switch (i) {" +
+            "            case null: yield 0;" +
+            "            case 0, 1: yield 1;" +
+            "            default: yield 2;" +
+            "        }" +
+            "    }" +
+            "}";
+
+    private static final String EXPECTED =
+            "\n" +
+            "public class C {\n" +
+            "    \n" +
+            "    void t1(Integer i) {\n" +
+            "        switch (i) {\n" +
+            "        case null:\n" +
+            "            i++;\n" +
+            "            break;\n" +
+            "        \n" +
+            "        case 0, 1:\n" +
+            "            i++;\n" +
+            "            break;\n" +
+            "        \n" +
+            "        default:\n" +
+            "            i++;\n" +
+            "            break;\n" +
+            "        \n" +
+            "        }\n" +
+            "    }\n" +
+            "    \n" +
+            "    int t2(Integer i) {\n" +
+            "        return switch (i) {\n" +
+            "        case null:\n" +
+            "            yield 0;\n" +
+            "        \n" +
+            "        case 0, 1:\n" +
+            "            yield 1;\n" +
+            "        \n" +
+            "        default:\n" +
+            "            yield 2;\n" +
+            "        \n" +
+            "        };\n" +
+            "    }\n" +
+            "}";
+
+    public static void main(String[] args) throws Exception {
+        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
+        assert tool != null;
+        DiagnosticListener<JavaFileObject> noErrors = d -> {};
+        String sourceVersion = Integer.toString(Runtime.version().feature());
+
+        JavacTask ct = (JavacTask) tool.getTask(null, null, noErrors,
+            List.of("-XDdev", "--enable-preview", "-source", sourceVersion), null,
+            Arrays.asList(new MyFileObject(CODE)));
+        String actualCode = ct.parse().iterator().next().toString();
+        actualCode = actualCode.replace(System.getProperty("line.separator"), "\n");
+        if (!EXPECTED.equals(actualCode)) {
+            throw new AssertionError("Unexpected toString outcome: " +
+                                     actualCode);
+        }
+    }
+
+    static class MyFileObject extends SimpleJavaFileObject {
+        private String text;
+
+        public MyFileObject(String text) {
+            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
+            this.text = text;
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return text;
+        }
+    }
+}
--- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java	Wed Jun 12 10:02:49 2019 +0530
@@ -11,44 +11,44 @@
         int z = 42;
         int i = switch (z) {
             case 0 -> {
-                break 42;
+                yield 42;
                 System.out.println("Unreachable");  //Unreachable
             }
             default -> 0;
         };
         i = switch (z) {
             case 0 -> {
-                break 42;
-                break 42; //Unreachable
+                yield 42;
+                yield 42; //Unreachable
             }
             default -> 0;
         };
         i = switch (z) {
             case 0:
                 System.out.println("0");
-                break 42;
+                yield 42;
                 System.out.println("1");    //Unreachable
-            default : break 42;
+            default : yield 42;
         };
         i = switch (z) {
             case 0 -> 42;
             default -> {
-                break 42;
+                yield 42;
                 System.out.println("Unreachable"); //Unreachable
             }
         };
         i = switch (z) {
-            case 0: break 42;
+            case 0: yield 42;
             default:
                 System.out.println("0");
-                break 42;
+                yield 42;
                 System.out.println("1");    //Unreachable
         };
         i = switch (z) {
             case 0:
             default:
                 System.out.println("0");
-                break 42;
+                yield 42;
                 System.out.println("1");    //Unreachable
         };
     }
--- a/test/langtools/tools/javac/switchexpr/ParseIncomplete.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/ParseIncomplete.java	Wed Jun 12 10:02:49 2019 +0530
@@ -50,9 +50,9 @@
             "    }" +
             "    int t2(Integer i) {" +
             "        return switch (i) {" +
-            "            case null: break 0;" +
-            "            case 0, 1: break 1;" +
-            "            default: break 2;" +
+            "            case null: yield 0;" +
+            "            case 0, 1: yield 1;" +
+            "            default: yield 2;" +
             "        }" +
             "    }" +
             "}";
--- a/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java	Wed Jun 12 10:02:49 2019 +0530
@@ -38,7 +38,7 @@
             int dummy = 1 + switch (i) {
                 default -> {
                     i++;
-                    break 1;
+                    yield 1;
                 }
             };
             if (i != 1) {
@@ -51,7 +51,7 @@
                 case -1 -> 1;
                 default -> {
                     i++;
-                    break 1;
+                    yield 1;
                 }
             };
             if (i != 1) {
@@ -63,7 +63,7 @@
             int dummy = 1 + switch (i) {
                  default :
                     i++;
-                    break 1;
+                    yield 1;
             };
             if (i != 1) {
                 throw new IllegalStateException("Side effects missing.");
@@ -72,10 +72,10 @@
         {
             i = 0;
             int dummy = 1 + switch (i) {
-                case -1: break 1;
+                case -1: yield 1;
                 default:
                     i++;
-                    break 1;
+                    yield 1;
             };
             if (i != 1) {
                 throw new IllegalStateException("Side effects missing.");
--- a/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java	Wed Jun 12 10:02:49 2019 +0530
@@ -9,9 +9,9 @@
 
     private String scopesIsolated(int i) {
         return switch (i) {
-            case 0 -> { String res = ""; break res; }
-            case 1 -> { res = ""; break res; }
-            default -> { res = ""; break res; }
+            case 0 -> { String res = ""; yield res; }
+            case 1 -> { res = ""; yield res; }
+            default -> { res = ""; yield res; }
         };
     }
 
--- a/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -38,6 +38,7 @@
 
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.tree.SwitchExpressionTree;
+import com.sun.source.tree.YieldTree;
 import com.sun.source.tree.Tree;
 import com.sun.source.util.JavacTask;
 import com.sun.source.util.SimpleTreeVisitor;
@@ -53,12 +54,13 @@
         String code = "class Test {\n" +
                       "    int t(int i) {\n" +
                       "         return switch(i) {\n" +
-                      "              default: break -1;\n" +
+                      "              default: yield -1;\n" +
                       "         }\n" +
                       "    }\n" +
                       "}\n";
         int[] callCount = new int[1];
         int[] switchExprNodeCount = new int[1];
+        int[] yieldNodeCount = new int[1];
         new TreePathScanner<Void, Void>() {
             @Override
             public Void visitSwitchExpression(SwitchExpressionTree node, Void p) {
@@ -74,11 +76,27 @@
                 }, null);
                 return super.visitSwitchExpression(node, p);
             }
+            @Override
+            public Void visitYield(YieldTree node, Void p) {
+                node.accept(new SimpleTreeVisitor<Void, Void>() {
+                    @Override
+                    protected Void defaultAction(Tree defaultActionNode, Void p) {
+                        callCount[0]++;
+                        if (node == defaultActionNode) {
+                            yieldNodeCount[0]++;
+                        }
+                        return null;
+                    }
+                }, null);
+                return super.visitYield(node, p);
+            }
         }.scan(parse(code), null);
 
-        if (callCount[0] != 1 || switchExprNodeCount[0] != 1) {
+        if (callCount[0] != 2 || switchExprNodeCount[0] != 1 ||
+            yieldNodeCount[0] != 1) {
             throw new AssertionError("Unexpected counts; callCount=" + callCount[0] +
-                                     ", switchExprNodeCount=" + switchExprNodeCount[0]);
+                                     ", switchExprNodeCount=" + switchExprNodeCount[0] +
+                                     ", yieldNodeCount=" + yieldNodeCount[0]);
         }
     }
 
--- a/test/langtools/tools/javac/switchexpr/TryCatch.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchexpr/TryCatch.java	Wed Jun 12 10:02:49 2019 +0530
@@ -38,34 +38,34 @@
                         case 1:
                             try {
                                 new TryCatch().throwException();
-                                break -1;
+                                yield -1;
                             } catch(Throwable ex) {
-                                break val;
+                                yield val;
                             }
-                        default: break -1;
+                        default: yield -1;
                     };
                     case 1 -> {
                         try {
-                            break new TryCatch().id(switch (p + 1) {
+                            yield new TryCatch().id(switch (p + 1) {
                                 case 2:
                                     try {
                                         new TryCatch().throwException();
-                                        break -1;
+                                        yield -1;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break -1;
+                                default: yield -1;
                             });
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break -1;
+                            yield -1;
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                 } - 1);
@@ -83,34 +83,34 @@
                         case 1:
                             try {
                                 new TryCatch().throwException();
-                                break false;
+                                yield false;
                             } catch(Throwable ex) {
-                                break true;
+                                yield true;
                             }
-                        default: break false;
+                        default: yield false;
                     };
                     case 1 -> {
                         try {
-                            break new TryCatch().id(switch (p + 1) {
+                            yield new TryCatch().id(switch (p + 1) {
                                 case 2:
                                     try {
                                         new TryCatch().throwException();
-                                        break false;
+                                        yield false;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break false;
+                                default: yield false;
                             });
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break false;
+                            yield false;
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                 } && (x = 1) == 1 && x == 1 ? val : -1);
@@ -127,34 +127,34 @@
                         case B:
                             try {
                                 new TryCatch().throwException();
-                                break -1;
+                                yield -1;
                             } catch(Throwable ex) {
-                                break val;
+                                yield val;
                             }
-                        default: break -1;
+                        default: yield -1;
                     };
                     case B -> {
                         try {
-                            break new TryCatch().id(switch (e.next()) {
+                            yield new TryCatch().id(switch (e.next()) {
                                 case C:
                                     try {
                                         new TryCatch().throwException();
-                                        break -1;
+                                        yield -1;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break -1;
+                                default: yield -1;
                             });
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break -1;
+                            yield -1;
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                 } - 1);
@@ -172,34 +172,34 @@
                         case B:
                             try {
                                 new TryCatch().throwException();
-                                break false;
+                                yield false;
                             } catch(Throwable ex) {
-                                break true;
+                                yield true;
                             }
-                        default: break false;
+                        default: yield false;
                     };
                     case B -> {
                         try {
-                            break new TryCatch().id(switch (e.next()) {
+                            yield new TryCatch().id(switch (e.next()) {
                                 case C:
                                     try {
                                         new TryCatch().throwException();
-                                        break false;
+                                        yield false;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break false;
+                                default: yield false;
                             });
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break false;
+                            yield false;
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                 } && (x = 1) == 1 && x == 1 ? val : -1);
@@ -216,34 +216,34 @@
                         case "c":
                             try {
                                 new TryCatch().throwException();
-                                break -1;
+                                yield -1;
                             } catch(Throwable ex) {
-                                break val;
+                                yield val;
                             }
-                        default: break -1;
+                        default: yield -1;
                     };
                     case "a" -> {
                         try {
-                            break new TryCatch().id(switch (s + "c") {
+                            yield new TryCatch().id(switch (s + "c") {
                                 case "ac":
                                     try {
                                         new TryCatch().throwException();
-                                        break -1;
+                                        yield -1;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break -1;
+                                default: yield -1;
                             });
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break -1;
+                            yield -1;
                         } catch(Throwable ex) {
-                            break val;
+                            yield val;
                         }
                     }
                 } - 1);
@@ -261,34 +261,34 @@
                         case "c":
                             try {
                                 new TryCatch().throwException();
-                                break false;
+                                yield false;
                             } catch(Throwable ex) {
-                                break true;
+                                yield true;
                             }
-                        default: break false;
+                        default: yield false;
                     };
                     case "a" -> {
                         try {
-                            break new TryCatch().id(switch (s + "c") {
+                            yield new TryCatch().id(switch (s + "c") {
                                 case "ac":
                                     try {
                                         new TryCatch().throwException();
-                                        break false;
+                                        yield false;
                                     } catch(Throwable ex) {
                                         throw ex;
                                     }
-                                default: break false;
+                                default: yield false;
                             });
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                     default -> {
                         try {
                             new TryCatch().throwException();
-                            break false;
+                            yield false;
                         } catch(Throwable ex) {
-                            break true;
+                            yield true;
                         }
                     }
                 } && (x = 1) == 1 && x == 1 ? val : -1);
@@ -330,75 +330,75 @@
 
     static class FieldHolder {
         private final int intTest = switch (0) {
-            case -1: break -1;
+            case -1: yield -1;
             default:
                 try {
-                    break new TryCatch().id(switch (2) {
+                    yield new TryCatch().id(switch (2) {
                         case 2:
                             try {
                                 new TryCatch().throwException();
-                                break -1;
+                                yield -1;
                             } catch(Throwable ex) {
                                 throw ex;
                             }
-                        default: break -1;
+                        default: yield -1;
                     });
                 } catch(Throwable ex) {
-                    break 3;
+                    yield 3;
                 }
         };
         private static final int intStaticTest = switch (0) {
-            case -1: break -1;
+            case -1: yield -1;
             default:
                 try {
-                    break new TryCatch().id(switch (2) {
+                    yield new TryCatch().id(switch (2) {
                         case 2:
                             try {
                                 new TryCatch().throwException();
-                                break -1;
+                                yield -1;
                             } catch(Throwable ex) {
                                 throw ex;
                             }
-                        default: break -1;
+                        default: yield -1;
                     });
                 } catch(Throwable ex) {
-                    break 3;
+                    yield 3;
                 }
         };
         private final boolean booleanTest = switch (0) {
-            case -1: break false;
+            case -1: yield false;
             default:
                 try {
-                    break new TryCatch().id(switch (2) {
+                    yield new TryCatch().id(switch (2) {
                         case 2:
                             try {
                                 new TryCatch().throwException();
-                                break false;
+                                yield false;
                             } catch(Throwable ex) {
                                 throw ex;
                             }
-                        default: break false;
+                        default: yield false;
                     });
                 } catch(Throwable ex) {
-                    break true;
+                    yield true;
                 }
         };
         private static final boolean booleanStaticTest = switch (0) {
-            case -1: break false;
+            case -1: yield false;
             default:
                 try {
-                    break new TryCatch().id(switch (2) {
+                    yield new TryCatch().id(switch (2) {
                         case 2:
                             try {
                                 new TryCatch().throwException();
-                                break false;
+                                yield false;
                             } catch(Throwable ex) {
                                 throw ex;
                             }
-                        default: break false;
+                        default: yield false;
                     });
                 } catch(Throwable ex) {
-                    break true;
+                    yield true;
                 }
         };
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WarnWrongYieldTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8223305
+ * @summary Verify correct warnings w.r.t. yield
+ * @compile/ref=WarnWrongYieldTest.out -source 13 -XDrawDiagnostics -XDshould-stop.at=ATTR WarnWrongYieldTest.java
+ */
+
+package t;
+
+//ERROR - type called yield:
+import t.WarnWrongYieldTest.yield;
+
+public class WarnWrongYieldTest {
+
+    // ERROR -  class called yield
+    class yield { }
+
+    // OK to have fields called yield
+    String[] yield = null;
+
+    // ERROR - field of type yield
+    yield y;
+
+    // OK to have methods called yield
+    // Nullary yield method
+    String[] yield() {
+        return null;
+    }
+    // Unary yield method
+    String[] yield(int i) {
+        return null;
+    }
+    // Binary yield method
+    String[] yield(int i, int j) {
+        return null;
+    }
+
+    // OK to declare a local called yield
+    void LocalDeclaration1() {
+       int yield;
+    }
+    // OK to declare and initialise a local called yield
+    void LocalDeclaration2() {
+        int yield = 42;
+    }
+
+    void YieldTypedLocals(int i) {
+        // ERROR - Parsed as yield statement, and y1 is unknown
+        yield y1 = null;
+
+        // ERROR - Parsed as yield statement, and y2 is unknown
+        yield y2 = new yield();
+
+        // ERROR - can not create an yield-valued local of type Object
+        Object y3 = new yield();
+
+        // ERROR - can not create a final yield-valued local of type yield
+        final yield y4 = new yield();
+
+        // ERROR - can create a non-final local of type yield using qualified typename
+        WarnWrongYieldTest.yield y5 = new yield();
+    }
+
+    void MethodInvocation(int i) {
+
+        // OK - can access a field called yield
+        String[] x = this.yield;
+
+        // ERROR - calling nullary yield method using simple name parsed as yield statement
+        yield();
+        // OK - can call nullary yield method using qualified name
+        this.yield();
+
+        // ERROR - Calling unary yield method using simple name is parsed as yield statement
+        yield(2);
+        // OK - calling unary yield method using qualified name
+        this.yield(2);
+
+        // ERROR - Calling binary yield method using simple name is parsed as yield statement
+        yield(2, 2); //error
+        // OK - calling binary yield method using qualified name
+        this.yield(2, 2);
+
+        // ERROR - nullary yield method as receiver is parsed as yield statement
+        yield().toString();
+        // OK - nullary yield method as receiver using qualified name
+        this.yield().toString();
+
+        // ERROR - unary yield method as receiver is parsed as yield statement
+        yield(2).toString();
+        // OK - unary yield method as receiver using qualified name
+        this.yield(2).toString();
+
+        // ERROR - binary yield method as receiver is parsed as yield statement
+        yield(2, 2).toString();
+        // OK - binary yield method as receiver using qualified name
+        this.yield(2, 2).toString();
+
+        // OK - yield method call is in an expression position
+        String str = yield(2).toString();
+
+        //OK - yield is a variable
+        yield.toString();
+
+        // OK - parsed as method call (with qualified local yield as receiver)
+        this.yield.toString();
+
+        yield[0].toString(); //error
+    }
+
+    private void yieldLocalVar1(int i) {
+        int yield = 0;
+
+        //OK - yield is a variable:
+        yield++;
+        yield--;
+
+        //OK - yield is a variable:
+        yield = 3;
+
+        //OK - yield is a variable:
+        for (int j = 0; j < 3; j++)
+            yield += 1;
+
+        //OK - yield is a variable and not at the beginning of the statement:
+        yieldLocalVar1(yield);
+
+        //ERROR - unqualified yield method invocation:
+        yieldLocalVar1(yield().length);
+        yieldLocalVar1(yield.class.getModifiers());
+    }
+
+    private void yieldLocalVar2(int i) {
+        int[] yield = new int[1];
+
+        //OK - yield is a variable:
+        yield[0] = 5;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WarnWrongYieldTest.out	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,25 @@
+WarnWrongYieldTest.java:39:11: compiler.warn.restricted.type.not.allowed.preview: yield, 13
+WarnWrongYieldTest.java:45:5: compiler.warn.restricted.type.not.allowed.preview: yield, 13
+WarnWrongYieldTest.java:72:15: compiler.warn.restricted.type.not.allowed.preview: yield, 13
+WarnWrongYieldTest.java:75:15: compiler.warn.restricted.type.not.allowed.preview: yield, 13
+WarnWrongYieldTest.java:81:21: compiler.warn.restricted.type.not.allowed.preview: yield, 13
+WarnWrongYieldTest.java:93:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:98:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:103:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:108:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:113:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:118:9: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:123:22: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:152:24: compiler.warn.invalid.yield
+WarnWrongYieldTest.java:34:28: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:45:5: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:72:9: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:75:9: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:75:24: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:78:25: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:81:15: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:81:30: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:84:27: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:84:43: compiler.warn.illegal.ref.to.restricted.type: yield
+WarnWrongYieldTest.java:153:24: compiler.warn.illegal.ref.to.restricted.type: yield
+24 warnings
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WrongBreakTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8223305
+ * @summary Ensure javac is not crashing for wrong breaks.
+ * @compile/fail/ref=WrongBreakTest.out --enable-preview -source ${jdk.version} -XDrawDiagnostics -XDshould-stop.at=FLOW WrongBreakTest.java
+ */
+
+public class WrongBreakTest {
+
+    void test(int i) {
+        int s = 0;
+        int j = switch (s) { default: break; };
+        test(switch (s) { default: yield; });
+        Runnable r = () -> {
+            yield 15;
+        };
+        while (true) {
+            yield 15;
+        }
+    }
+
+    void test(Object o) {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WrongBreakTest.out	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,8 @@
+WrongBreakTest.java:36:41: compiler.err.illegal.start.of.expr
+WrongBreakTest.java:35:39: compiler.err.break.outside.switch.expression
+WrongBreakTest.java:36:9: compiler.err.ref.ambiguous: test, kindname.method, test(int), WrongBreakTest, kindname.method, test(java.lang.Object), WrongBreakTest
+WrongBreakTest.java:38:13: compiler.err.no.switch.expression
+WrongBreakTest.java:41:13: compiler.err.no.switch.expression
+- compiler.note.preview.filename: WrongBreakTest.java
+- compiler.note.preview.recompile
+5 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WrongYieldTest.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8223305
+ * @summary Ensure proper errors are returned for yields.
+ * @compile/fail/ref=WrongYieldTest.out --enable-preview -source ${jdk.version} -XDrawDiagnostics -XDshould-stop.at=ATTR WrongYieldTest.java
+ */
+
+package t;
+
+//ERROR - type called yield:
+import t.WrongYieldTest.yield;
+
+public class WrongYieldTest {
+
+    // ERROR -  class called yield
+    class yield { }
+
+    // OK to have fields called yield
+    String[] yield = null;
+
+    // ERROR - field of type yield
+    yield y;
+
+    // OK to have methods called yield
+    // Nullary yield method
+    String[] yield() {
+        return null;
+    }
+    // Unary yield method
+    String[] yield(int i) {
+        return null;
+    }
+    // Binary yield method
+    String[] yield(int i, int j) {
+        return null;
+    }
+
+    // OK to declare a local called yield
+    void LocalDeclaration1() {
+       int yield;
+    }
+    // OK to declare and initialise a local called yield
+    void LocalDeclaration2() {
+        int yield = 42;
+    }
+    // ERROR can't refer to a local called yield in the initialiser
+    void LocalDeclaration3() {
+        int yield = yield + 1;
+    }
+
+    // OK yield gets interpreted as an identifier in a local declaration
+    void LocalDeclaration4(int i) {
+        int local = switch (i) {
+            default -> {
+                int yield = yield + 1;
+                yield 42;
+            }
+        };
+    }
+    // OK - yield a local called yield
+    void LocalDeclaration5(int i) {
+        int yield = 42;
+        int temp = switch (i) {
+            default -> {
+                yield yield;
+            }
+        };
+    }
+
+    void YieldTypedLocals(int i) {
+        // ERROR - Parsed as yield statement, and y1 is unknown
+        yield y1 = null;
+        // ..whereas..
+        // ERROR - parsed as yield statement, which has no switch target
+        Object y1;
+        yield y1 = null;
+
+        // ERROR - Parsed as yield statement, and y2 is unknown
+        yield y2 = new yield();
+
+        // OK - Parsed as yield statement that assigns local y
+        Object y;
+        Object o = switch (i) {
+            default :
+                yield y = null;
+        };
+
+        // ERROR - Parsed as yield statement that assigns local y,
+        //but the initializer refers to restricted identifier:
+        Object y2;
+        Object o2 = switch (i) {
+            default :
+                yield y2 = new yield();
+        };
+
+        // ERROR - can not create an yield-valued local of type Object
+        Object y3 = new yield();
+
+        // ERROR - can not create a final yield-valued local of type yield
+        final yield y4 = new yield();
+
+        // ERROR - can create a non-final local of type yield using qualified typename
+        WrongYieldTest.yield y5 = new yield();
+
+    }
+
+    void MethodInvocation(int i) {
+
+        // OK - can access a field called yield
+        String[] x = this.yield;
+
+        // ERROR - calling nullary yield method using simple name parsed as yield statement
+        yield();
+        // OK - can call nullary yield method using qualified name
+        this.yield();
+
+        // ERROR - Calling unary yield method using simple name is parsed as yield statement
+        yield(2);
+        // OK - calling unary yield method using qualified name
+        this.yield(2);
+
+        // ERROR - Calling binary yield method using simple name is parsed as yield statement
+        yield(2, 2); //error
+        // OK - calling binary yield method using qualified name
+        this.yield(2, 2);
+
+        // ERROR - nullary yield method as receiver is parsed as yield statement
+        yield().toString();
+        // OK - nullary yield method as receiver using qualified name
+        this.yield().toString();
+
+        // ERROR - unary yield method as receiver is parsed as yield statement
+        yield(2).toString();
+        // OK - unary yield method as receiver using qualified name
+        this.yield(2).toString();
+
+        // ERROR - binary yield method as receiver is parsed as yield statement
+        yield(2, 2).toString();
+        // OK - binary yield method as receiver using qualified name
+        this.yield(2, 2).toString();
+
+        // OK - yield method call is in an expression position
+        String str = yield(2).toString();
+
+
+
+        //OK - yield is a variable
+        yield.toString();
+
+        // OK - parsed as method call (with qualified local yield as receiver)
+        this.yield.toString();
+
+        yield[0].toString(); //error
+
+        // OK - parsed as yield statement in switch expression
+        int j = switch (i) {
+            default:
+                yield(2);
+        };
+
+        // ERROR - second yield is an unreachable statement.
+        x = switch (i) {
+            default: {
+                yield x = null;
+                yield null;
+            }
+        };
+    }
+
+    private void yieldLocalVar1(int i) {
+        int yield = 0;
+
+        //OK - yield is a variable:
+        yield++;
+        yield--;
+
+        //ERROR - yield is a statement, but no enclosing switch expr:
+        yield ++i;
+        yield --i;
+
+        //OK - yield is a variable:
+        yield = 3;
+
+        //OK - yield is a variable:
+        for (int j = 0; j < 3; j++)
+            yield += 1;
+
+        //OK - yield is a variable and not at the beginning of the statement:
+        yieldLocalVar1(yield);
+
+        //ERROR - unqualified yield method invocation:
+        yieldLocalVar1(yield().length);
+        yieldLocalVar1(yield.class.getModifiers());
+    }
+
+    private void yieldLocalVar2(int i) {
+        int[] yield = new int[1];
+
+        //OK - yield is a variable:
+        yield[0] = 5;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchexpr/WrongYieldTest.out	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,29 @@
+WrongYieldTest.java:39:11: compiler.err.restricted.type.not.allowed: yield, 13
+WrongYieldTest.java:45:5: compiler.err.restricted.type.not.allowed.here: yield
+WrongYieldTest.java:136:9: compiler.err.invalid.yield
+WrongYieldTest.java:146:9: compiler.err.invalid.yield
+WrongYieldTest.java:151:9: compiler.err.invalid.yield
+WrongYieldTest.java:161:9: compiler.err.invalid.yield
+WrongYieldTest.java:166:22: compiler.err.invalid.yield
+WrongYieldTest.java:215:24: compiler.err.invalid.yield
+WrongYieldTest.java:34:24: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:95:9: compiler.err.no.switch.expression
+WrongYieldTest.java:95:15: compiler.err.cant.resolve.location: kindname.variable, y1, , , (compiler.misc.location: kindname.class, t.WrongYieldTest, null)
+WrongYieldTest.java:99:9: compiler.err.no.switch.expression
+WrongYieldTest.java:102:9: compiler.err.no.switch.expression
+WrongYieldTest.java:102:15: compiler.err.cant.resolve.location: kindname.variable, y2, , , (compiler.misc.location: kindname.class, t.WrongYieldTest, null)
+WrongYieldTest.java:102:24: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:116:32: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:120:25: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:123:30: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:126:23: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:126:39: compiler.err.illegal.ref.to.restricted.type: yield
+WrongYieldTest.java:141:9: compiler.err.no.switch.expression.qualify
+WrongYieldTest.java:156:9: compiler.err.no.switch.expression
+WrongYieldTest.java:156:17: compiler.err.cant.deref: int
+WrongYieldTest.java:201:9: compiler.err.no.switch.expression
+WrongYieldTest.java:202:9: compiler.err.no.switch.expression
+WrongYieldTest.java:216:24: compiler.err.illegal.ref.to.restricted.type: yield
+- compiler.note.preview.filename: WrongYieldTest.java
+- compiler.note.preview.recompile
+26 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchextra/DefiniteAssignment1.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @summary Verify that definite assignment works (legal code)
+ * @compile --enable-preview -source ${jdk.version} DefiniteAssignment1.java
+ * @run main/othervm --enable-preview DefiniteAssignment1
+ */
+public class DefiniteAssignment1 {
+    public static void main(String[] args) {
+        int a = 0;
+
+        {
+        int x;
+
+        switch(a) {
+            case 0: x = 0; break;
+            default: x = 1; break;
+        }
+
+        if (x != 0)
+            throw new IllegalStateException("Unexpected value.");
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 1: x = 1; break;
+            case 0:
+            default: x = 0; break;
+        }
+
+        if (x != 0)
+            throw new IllegalStateException("Unexpected value.");
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 1: x = 1; break;
+            case 0:
+            default: x = 0;
+        }
+
+        if (x != 0)
+            throw new IllegalStateException("Unexpected value.");
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 0 -> x = 0;
+            default -> x = 1;
+        }
+
+        if (x != 0)
+            throw new IllegalStateException("Unexpected value.");
+        }
+
+        {
+        int x;
+
+        try {
+            switch(a) {
+                case 1: x = 1; break;
+                case 0:
+                default: throw new UnsupportedOperationException();
+            }
+
+            throw new IllegalStateException("Unexpected value: " + x);
+            } catch (UnsupportedOperationException ex) {
+                //OK
+            }
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 0 -> x = 0;
+            default -> throw new IllegalStateException();
+        }
+
+        if (x != 0)
+            throw new IllegalStateException("Unexpected value.");
+        }
+    }
+
+    enum E {
+        A, B, C;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchextra/DefiniteAssignment2.java	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,80 @@
+/**
+ * @test /nodynamiccopyright/
+ * @summary Verify that definite assignment works (illegal code)
+ * @compile/fail/ref=DefiniteAssignment2.out -XDrawDiagnostics --enable-preview -source ${jdk.version} DefiniteAssignment2.java
+ */
+public class DefiniteAssignment2 {
+
+    public static void main(String[] args) {
+        int a = 0;
+        E e = E.A;
+
+        {
+        int x;
+
+        switch(a) {
+            case 0: break;
+            default: x = 1; break;
+        }
+
+        System.err.println(x);
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 0 -> {}
+            default -> x = 1;
+        }
+
+        System.err.println(x);
+        }
+
+        {
+        int x;
+
+        switch(a) {
+            case 0: x = 0; break;
+            default:
+        }
+
+        System.err.println(x);
+        }
+
+        {
+        int x;
+
+        switch(e) {
+            case A, B, C -> x = 0;
+        }
+
+        System.err.println(x);
+        }
+
+        {
+        int x;
+
+        switch(e) {
+            case A, B, C -> { x = 0; }
+        }
+
+        System.err.println(x);
+        }
+
+        {
+        int x;
+
+        switch(e) {
+            case A, B -> { x = 0; }
+            case C -> throw new IllegalStateException();
+        }
+
+        System.err.println(x);
+        }
+    }
+
+    enum E {
+        A, B, C;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/switchextra/DefiniteAssignment2.out	Wed Jun 12 10:02:49 2019 +0530
@@ -0,0 +1,9 @@
+DefiniteAssignment2.java:20:28: compiler.err.var.might.not.have.been.initialized: x
+DefiniteAssignment2.java:31:28: compiler.err.var.might.not.have.been.initialized: x
+DefiniteAssignment2.java:42:28: compiler.err.var.might.not.have.been.initialized: x
+DefiniteAssignment2.java:52:28: compiler.err.var.might.not.have.been.initialized: x
+DefiniteAssignment2.java:62:28: compiler.err.var.might.not.have.been.initialized: x
+DefiniteAssignment2.java:73:28: compiler.err.var.might.not.have.been.initialized: x
+- compiler.note.preview.filename: DefiniteAssignment2.java
+- compiler.note.preview.recompile
+6 errors
--- a/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java	Wed Jun 12 10:02:49 2019 +0530
@@ -30,7 +30,7 @@
     private String expression1(T t) {
         return switch (t) {
             case A -> "A";
-            case B, C -> { break "B-C"; }
+            case B, C -> { yield "B-C"; }
             case D -> "D";
             default -> "other";
         };
--- a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out	Wed Jun 12 10:02:49 2019 +0530
@@ -2,5 +2,5 @@
 VarInImplicitLambdaNegTest01.java:13:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.implicit.not.allowed)
 VarInImplicitLambdaNegTest01.java:14:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.explicit.not.allowed)
 VarInImplicitLambdaNegTest01.java:15:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed)
-VarInImplicitLambdaNegTest01.java:17:52: compiler.err.var.not.allowed.array
+VarInImplicitLambdaNegTest01.java:17:52: compiler.err.restricted.type.not.allowed.array: var
 5 errors
--- a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out	Tue Jun 11 17:15:25 2019 -0700
+++ b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out	Wed Jun 12 10:02:49 2019 +0530
@@ -1,6 +1,6 @@
 - compiler.warn.source.no.bootclasspath: 10
 VarInImplicitLambdaNegTest01.java:12:36: compiler.err.feature.not.supported.in.source.plural: (compiler.misc.feature.var.syntax.in.implicit.lambda), 10, 11
 VarInImplicitLambdaNegTest01.java:15:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed)
-VarInImplicitLambdaNegTest01.java:17:52: compiler.err.var.not.allowed.here
+VarInImplicitLambdaNegTest01.java:17:52: compiler.err.restricted.type.not.allowed.here: var
 3 errors
 1 warning