changeset 19216:14f932255354

Merge
author lana
date Tue, 06 Aug 2013 17:01:05 -0700
parents e5901820c3c1 bbe43d712fe0
children e1b733e060c6
files nashorn/src/jdk/internal/dynalink/beans/SafeUnreflector.java nashorn/src/jdk/internal/dynalink/beans/SafeUnreflectorImpl.java nashorn/src/jdk/internal/dynalink/beans/SandboxClassLoader.java nashorn/src/jdk/internal/dynalink/beans/sandbox/Unreflector.java nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterGeneratorBase.java nashorn/test/script/representations/NASHORN-592a.js
diffstat 252 files changed, 15171 insertions(+), 2192 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 711eb4aa87de68de78250e0549980936bab53d54 jdk8-b98
 2d3875b0d18b3ad1c2bebf385a697e309e4005a4 jdk8-b99
 3d34036aae4ea90b2ca59712d5a69db3221f0875 jdk8-b100
+edb01c460d4cab21ff0ff13512df7b746efaa0e7 jdk8-b101
--- a/.hgtags-top-repo	Fri Jun 28 16:26:54 2013 -0400
+++ b/.hgtags-top-repo	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98
 59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99
 d2dcb110e9dbaf9903c05b211df800e78e4b394e jdk8-b100
+9f74a220677dc265a724515d8e2617548cef62f1 jdk8-b101
--- a/corba/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/corba/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98
 3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99
 8d492f1dfd1b131a4c7886ee6b59528609f7e4fe jdk8-b100
+a013024b07475782f1fa8e196e950b34b4077663 jdk8-b101
--- a/hotspot/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -363,3 +363,5 @@
 9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42
 5787fac72e760c6a5fd9efa113b0c75caf554136 jdk8-b100
 46487ba40ff225654d0c51787ed3839bafcbd9f3 hs25-b43
+f6921c876db192bba389cec062855a66372da01c jdk8-b101
+530fe88b3b2c710f42810b3580d86a0d83ad6c1c hs25-b44
--- a/hotspot/make/bsd/makefiles/minimal1.make	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/make/bsd/makefiles/minimal1.make	Tue Aug 06 17:01:05 2013 -0700
@@ -24,16 +24,20 @@
 
 TYPE=MINIMAL1
 
-INCLUDE_JVMTI ?= false
-INCLUDE_FPROF ?= false
-INCLUDE_VM_STRUCTS ?= false
-INCLUDE_JNI_CHECK ?= false
-INCLUDE_SERVICES ?= false
-INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALL_GCS ?= false
-INCLUDE_NMT ?= false
-INCLUDE_TRACE ?= false
-INCLUDE_CDS ?= false
+# Force all variables to false, overriding any other
+# setting that may have occurred in the makefiles. These
+# can still be overridden by passing the variable as an
+# argument to 'make'
+INCLUDE_JVMTI := false
+INCLUDE_FPROF := false
+INCLUDE_VM_STRUCTS := false
+INCLUDE_JNI_CHECK := false
+INCLUDE_SERVICES := false
+INCLUDE_MANAGEMENT := false
+INCLUDE_ALL_GCS := false
+INCLUDE_NMT := false
+INCLUDE_TRACE := false
+INCLUDE_CDS := false
 
 CXXFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
 CFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
--- a/hotspot/make/hotspot_version	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/make/hotspot_version	Tue Aug 06 17:01:05 2013 -0700
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=43
+HS_BUILD_NUMBER=44
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/make/linux/makefiles/minimal1.make	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/make/linux/makefiles/minimal1.make	Tue Aug 06 17:01:05 2013 -0700
@@ -24,16 +24,20 @@
 
 TYPE=MINIMAL1
 
-INCLUDE_JVMTI ?= false
-INCLUDE_FPROF ?= false
-INCLUDE_VM_STRUCTS ?= false
-INCLUDE_JNI_CHECK ?= false
-INCLUDE_SERVICES ?= false
-INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALL_GCS ?= false
-INCLUDE_NMT ?= false
-INCLUDE_TRACE ?= false
-INCLUDE_CDS ?= false
+# Force all variables to false, overriding any other
+# setting that may have occurred in the makefiles. These
+# can still be overridden by passing the variable as an
+# argument to 'make'
+INCLUDE_JVMTI := false
+INCLUDE_FPROF := false
+INCLUDE_VM_STRUCTS := false
+INCLUDE_JNI_CHECK := false
+INCLUDE_SERVICES := false
+INCLUDE_MANAGEMENT := false
+INCLUDE_ALL_GCS := false
+INCLUDE_NMT := false
+INCLUDE_TRACE := false
+INCLUDE_CDS := false
 
 CXXFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
 CFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
--- a/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -42,7 +42,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            false);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            140000);
 
--- a/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -44,7 +44,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            false);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            100000);
 
--- a/hotspot/src/share/vm/ci/ciReplay.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/ci/ciReplay.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -299,7 +299,7 @@
     Symbol* method_signature = parse_symbol(CHECK_NULL);
     Method* m = k->find_method(method_name, method_signature);
     if (m == NULL) {
-      report_error("can't find method");
+      report_error("Can't find method");
     }
     return m;
   }
@@ -398,8 +398,8 @@
 
   // compile <klass> <name> <signature> <entry_bci> <comp_level>
   void process_compile(TRAPS) {
-    // methodHandle method;
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     int entry_bci = parse_int("entry_bci");
     const char* comp_level_label = "comp_level";
     int comp_level = parse_int(comp_level_label);
@@ -440,6 +440,7 @@
   //
   void process_ciMethod(TRAPS) {
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     ciMethodRecord* rec = new_ciMethod(method);
     rec->invocation_counter = parse_int("invocation_counter");
     rec->backedge_counter = parse_int("backedge_counter");
@@ -451,6 +452,7 @@
   // ciMethodData <klass> <name> <signature> <state> <current mileage> orig <length> # # ... data <length> # # ... oops <length>
   void process_ciMethodData(TRAPS) {
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     /* jsut copied from Method, to build interpret data*/
     if (InstanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
       return;
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -122,6 +122,22 @@
   }
 };
 
+class Par_MarkRefsIntoClosure: public CMSOopsInGenClosure {
+ private:
+  const MemRegion _span;
+  CMSBitMap*      _bitMap;
+ protected:
+  DO_OOP_WORK_DEFN
+ public:
+  Par_MarkRefsIntoClosure(MemRegion span, CMSBitMap* bitMap);
+  virtual void do_oop(oop* p);
+  virtual void do_oop(narrowOop* p);
+
+  Prefetch::style prefetch_style() {
+    return Prefetch::do_read;
+  }
+};
+
 // A variant of the above used in certain kinds of CMS
 // marking verification.
 class MarkRefsIntoVerifyClosure: public CMSOopsInGenClosure {
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -569,6 +569,7 @@
   _restart_addr(NULL),
   _overflow_list(NULL),
   _stats(cmsGen),
+  _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)),
   _eden_chunk_array(NULL),     // may be set in ctor body
   _eden_chunk_capacity(0),     // -- ditto --
   _eden_chunk_index(0),        // -- ditto --
@@ -732,7 +733,7 @@
   assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error");
 
   // Support for parallelizing survivor space rescan
-  if (CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) {
+  if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) {
     const size_t max_plab_samples =
       ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize;
 
@@ -2137,6 +2138,39 @@
 }
 
 
+void CMSCollector::print_eden_and_survivor_chunk_arrays() {
+  DefNewGeneration* dng = _young_gen->as_DefNewGeneration();
+  EdenSpace* eden_space = dng->eden();
+  ContiguousSpace* from_space = dng->from();
+  ContiguousSpace* to_space   = dng->to();
+  // Eden
+  if (_eden_chunk_array != NULL) {
+    gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
+                           eden_space->bottom(), eden_space->top(),
+                           eden_space->end(), eden_space->capacity());
+    gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", "
+                           "_eden_chunk_capacity=" SIZE_FORMAT,
+                           _eden_chunk_index, _eden_chunk_capacity);
+    for (size_t i = 0; i < _eden_chunk_index; i++) {
+      gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
+                             i, _eden_chunk_array[i]);
+    }
+  }
+  // Survivor
+  if (_survivor_chunk_array != NULL) {
+    gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
+                           from_space->bottom(), from_space->top(),
+                           from_space->end(), from_space->capacity());
+    gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", "
+                           "_survivor_chunk_capacity=" SIZE_FORMAT,
+                           _survivor_chunk_index, _survivor_chunk_capacity);
+    for (size_t i = 0; i < _survivor_chunk_index; i++) {
+      gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
+                             i, _survivor_chunk_array[i]);
+    }
+  }
+}
+
 void CMSCollector::getFreelistLocks() const {
   // Get locks for all free lists in all generations that this
   // collector is responsible for
@@ -3549,6 +3583,31 @@
 
 // CMS work
 
+// The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
+class CMSParMarkTask : public AbstractGangTask {
+ protected:
+  CMSCollector*     _collector;
+  int               _n_workers;
+  CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) :
+      AbstractGangTask(name),
+      _collector(collector),
+      _n_workers(n_workers) {}
+  // Work method in support of parallel rescan ... of young gen spaces
+  void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
+                             ContiguousSpace* space,
+                             HeapWord** chunk_array, size_t chunk_top);
+  void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
+};
+
+// Parallel initial mark task
+class CMSParInitialMarkTask: public CMSParMarkTask {
+ public:
+  CMSParInitialMarkTask(CMSCollector* collector, int n_workers) :
+      CMSParMarkTask("Scan roots and young gen for initial mark in parallel",
+                     collector, n_workers) {}
+  void work(uint worker_id);
+};
+
 // Checkpoint the roots into this generation from outside
 // this generation. [Note this initial checkpoint need only
 // be approximate -- we'll do a catch up phase subsequently.]
@@ -3646,19 +3705,42 @@
   // the klasses. The claimed marks need to be cleared before marking starts.
   ClassLoaderDataGraph::clear_claimed_marks();
 
-  CMKlassClosure klass_closure(&notOlder);
+  if (CMSPrintEdenSurvivorChunks) {
+    print_eden_and_survivor_chunk_arrays();
+  }
+
   {
     COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
-    gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
-    gch->gen_process_strong_roots(_cmsGen->level(),
-                                  true,   // younger gens are roots
-                                  true,   // activate StrongRootsScope
-                                  false,  // not scavenging
-                                  SharedHeap::ScanningOption(roots_scanning_options()),
-                                  &notOlder,
-                                  true,   // walk all of code cache if (so & SO_CodeCache)
-                                  NULL,
-                                  &klass_closure);
+    if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
+      // The parallel version.
+      FlexibleWorkGang* workers = gch->workers();
+      assert(workers != NULL, "Need parallel worker threads.");
+      int n_workers = workers->active_workers();
+      CMSParInitialMarkTask tsk(this, n_workers);
+      gch->set_par_threads(n_workers);
+      initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
+      if (n_workers > 1) {
+        GenCollectedHeap::StrongRootsScope srs(gch);
+        workers->run_task(&tsk);
+      } else {
+        GenCollectedHeap::StrongRootsScope srs(gch);
+        tsk.work(0);
+      }
+      gch->set_par_threads(0);
+    } else {
+      // The serial version.
+      CMKlassClosure klass_closure(&notOlder);
+      gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
+      gch->gen_process_strong_roots(_cmsGen->level(),
+                                    true,   // younger gens are roots
+                                    true,   // activate StrongRootsScope
+                                    false,  // not scavenging
+                                    SharedHeap::ScanningOption(roots_scanning_options()),
+                                    &notOlder,
+                                    true,   // walk all of code cache if (so & SO_CodeCache)
+                                    NULL,
+                                    &klass_closure);
+    }
   }
 
   // Clear mod-union table; it will be dirtied in the prologue of
@@ -4417,7 +4499,9 @@
   verify_overflow_empty();
   _abort_preclean = false;
   if (CMSPrecleaningEnabled) {
-    _eden_chunk_index = 0;
+    if (!CMSEdenChunksRecordAlways) {
+      _eden_chunk_index = 0;
+    }
     size_t used = get_eden_used();
     size_t capacity = get_eden_capacity();
     // Don't start sampling unless we will get sufficiently
@@ -4526,7 +4610,9 @@
   if (!_start_sampling) {
     return;
   }
-  if (_eden_chunk_array) {
+  // When CMSEdenChunksRecordAlways is true, the eden chunk array
+  // is populated by the young generation.
+  if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
     if (_eden_chunk_index < _eden_chunk_capacity) {
       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
@@ -5010,6 +5096,10 @@
     // Update the saved marks which may affect the root scans.
     gch->save_marks();
 
+    if (CMSPrintEdenSurvivorChunks) {
+      print_eden_and_survivor_chunk_arrays();
+    }
+
     {
       COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
 
@@ -5116,10 +5206,53 @@
   }
 }
 
+void CMSParInitialMarkTask::work(uint worker_id) {
+  elapsedTimer _timer;
+  ResourceMark rm;
+  HandleMark   hm;
+
+  // ---------- scan from roots --------------
+  _timer.start();
+  GenCollectedHeap* gch = GenCollectedHeap::heap();
+  Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
+  CMKlassClosure klass_closure(&par_mri_cl);
+
+  // ---------- young gen roots --------------
+  {
+    work_on_young_gen_roots(worker_id, &par_mri_cl);
+    _timer.stop();
+    if (PrintCMSStatistics != 0) {
+      gclog_or_tty->print_cr(
+        "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
+        worker_id, _timer.seconds());
+    }
+  }
+
+  // ---------- remaining roots --------------
+  _timer.reset();
+  _timer.start();
+  gch->gen_process_strong_roots(_collector->_cmsGen->level(),
+                                false,     // yg was scanned above
+                                false,     // this is parallel code
+                                false,     // not scavenging
+                                SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
+                                &par_mri_cl,
+                                true,   // walk all of code cache if (so & SO_CodeCache)
+                                NULL,
+                                &klass_closure);
+  assert(_collector->should_unload_classes()
+         || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
+         "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
+  _timer.stop();
+  if (PrintCMSStatistics != 0) {
+    gclog_or_tty->print_cr(
+      "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
+      worker_id, _timer.seconds());
+  }
+}
+
 // Parallel remark task
-class CMSParRemarkTask: public AbstractGangTask {
-  CMSCollector* _collector;
-  int           _n_workers;
+class CMSParRemarkTask: public CMSParMarkTask {
   CompactibleFreeListSpace* _cms_space;
 
   // The per-thread work queues, available here for stealing.
@@ -5133,10 +5266,9 @@
                    CompactibleFreeListSpace* cms_space,
                    int n_workers, FlexibleWorkGang* workers,
                    OopTaskQueueSet* task_queues):
-    AbstractGangTask("Rescan roots and grey objects in parallel"),
-    _collector(collector),
+    CMSParMarkTask("Rescan roots and grey objects in parallel",
+                   collector, n_workers),
     _cms_space(cms_space),
-    _n_workers(n_workers),
     _task_queues(task_queues),
     _term(n_workers, task_queues) { }
 
@@ -5150,11 +5282,6 @@
   void work(uint worker_id);
 
  private:
-  // Work method in support of parallel rescan ... of young gen spaces
-  void do_young_space_rescan(int i, Par_MarkRefsIntoAndScanClosure* cl,
-                             ContiguousSpace* space,
-                             HeapWord** chunk_array, size_t chunk_top);
-
   // ... of  dirty cards in old space
   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
                                   Par_MarkRefsIntoAndScanClosure* cl);
@@ -5186,6 +5313,25 @@
   }
 };
 
+void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
+  DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
+  EdenSpace* eden_space = dng->eden();
+  ContiguousSpace* from_space = dng->from();
+  ContiguousSpace* to_space   = dng->to();
+
+  HeapWord** eca = _collector->_eden_chunk_array;
+  size_t     ect = _collector->_eden_chunk_index;
+  HeapWord** sca = _collector->_survivor_chunk_array;
+  size_t     sct = _collector->_survivor_chunk_index;
+
+  assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
+  assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
+
+  do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
+  do_young_space_rescan(worker_id, cl, from_space, sca, sct);
+  do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
+}
+
 // work_queue(i) is passed to the closure
 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
 // also is passed to do_dirty_card_rescan_tasks() and to
@@ -5210,23 +5356,7 @@
   // work first.
   // ---------- young gen roots --------------
   {
-    DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
-    EdenSpace* eden_space = dng->eden();
-    ContiguousSpace* from_space = dng->from();
-    ContiguousSpace* to_space   = dng->to();
-
-    HeapWord** eca = _collector->_eden_chunk_array;
-    size_t     ect = _collector->_eden_chunk_index;
-    HeapWord** sca = _collector->_survivor_chunk_array;
-    size_t     sct = _collector->_survivor_chunk_index;
-
-    assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
-    assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
-
-    do_young_space_rescan(worker_id, &par_mrias_cl, to_space, NULL, 0);
-    do_young_space_rescan(worker_id, &par_mrias_cl, from_space, sca, sct);
-    do_young_space_rescan(worker_id, &par_mrias_cl, eden_space, eca, ect);
-
+    work_on_young_gen_roots(worker_id, &par_mrias_cl);
     _timer.stop();
     if (PrintCMSStatistics != 0) {
       gclog_or_tty->print_cr(
@@ -5334,8 +5464,8 @@
 
 // Note that parameter "i" is not used.
 void
-CMSParRemarkTask::do_young_space_rescan(int i,
-  Par_MarkRefsIntoAndScanClosure* cl, ContiguousSpace* space,
+CMSParMarkTask::do_young_space_rescan(uint worker_id,
+  OopsInGenClosure* cl, ContiguousSpace* space,
   HeapWord** chunk_array, size_t chunk_top) {
   // Until all tasks completed:
   // . claim an unclaimed task
@@ -5530,6 +5660,32 @@
          "Else our work is not yet done");
 }
 
+// Record object boundaries in _eden_chunk_array by sampling the eden
+// top in the slow-path eden object allocation code path and record
+// the boundaries, if CMSEdenChunksRecordAlways is true. If
+// CMSEdenChunksRecordAlways is false, we use the other asynchronous
+// sampling in sample_eden() that activates during the part of the
+// preclean phase.
+void CMSCollector::sample_eden_chunk() {
+  if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
+    if (_eden_chunk_lock->try_lock()) {
+      // Record a sample. This is the critical section. The contents
+      // of the _eden_chunk_array have to be non-decreasing in the
+      // address order.
+      _eden_chunk_array[_eden_chunk_index] = *_top_addr;
+      assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
+             "Unexpected state of Eden");
+      if (_eden_chunk_index == 0 ||
+          ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
+           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
+                          _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
+        _eden_chunk_index++;  // commit sample
+      }
+      _eden_chunk_lock->unlock();
+    }
+  }
+}
+
 // Return a thread-local PLAB recording array, as appropriate.
 void* CMSCollector::get_data_recorder(int thr_num) {
   if (_survivor_plab_array != NULL &&
@@ -5553,12 +5709,13 @@
 
 // Merge the per-thread plab arrays into the global survivor chunk
 // array which will provide the partitioning of the survivor space
-// for CMS rescan.
+// for CMS initial scan and rescan.
 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
                                               int no_of_gc_threads) {
   assert(_survivor_plab_array  != NULL, "Error");
   assert(_survivor_chunk_array != NULL, "Error");
-  assert(_collectorState == FinalMarking, "Error");
+  assert(_collectorState == FinalMarking ||
+         (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
   for (int j = 0; j < no_of_gc_threads; j++) {
     _cursor[j] = 0;
   }
@@ -5621,7 +5778,7 @@
 }
 
 // Set up the space's par_seq_tasks structure for work claiming
-// for parallel rescan of young gen.
+// for parallel initial scan and rescan of young gen.
 // See ParRescanTask where this is currently used.
 void
 CMSCollector::
@@ -6748,6 +6905,28 @@
 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
 
+Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
+  MemRegion span, CMSBitMap* bitMap):
+    _span(span),
+    _bitMap(bitMap)
+{
+    assert(_ref_processor == NULL, "deliberately left NULL");
+    assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
+}
+
+void Par_MarkRefsIntoClosure::do_oop(oop obj) {
+  // if p points into _span, then mark corresponding bit in _markBitMap
+  assert(obj->is_oop(), "expected an oop");
+  HeapWord* addr = (HeapWord*)obj;
+  if (_span.contains(addr)) {
+    // this should be made more efficient
+    _bitMap->par_mark(addr);
+  }
+}
+
+void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
+void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
+
 // A variant of the above, used for CMS marking verification.
 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
@@ -9305,7 +9484,6 @@
     return;
   }
 }
-
 // Transfer some number of overflown objects to usual marking
 // stack. Return true if some objects were transferred.
 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
@@ -9377,4 +9555,3 @@
       ShouldNotReachHere();
   }
 }
-
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -515,6 +515,8 @@
   friend class ConcurrentMarkSweepThread;
   friend class ConcurrentMarkSweepGeneration;
   friend class CompactibleFreeListSpace;
+  friend class CMSParMarkTask;
+  friend class CMSParInitialMarkTask;
   friend class CMSParRemarkTask;
   friend class CMSConcMarkingTask;
   friend class CMSRefProcTaskProxy;
@@ -749,6 +751,7 @@
   Generation* _young_gen;  // the younger gen
   HeapWord** _top_addr;    // ... Top of Eden
   HeapWord** _end_addr;    // ... End of Eden
+  Mutex*     _eden_chunk_lock;
   HeapWord** _eden_chunk_array; // ... Eden partitioning array
   size_t     _eden_chunk_index; // ... top (exclusive) of array
   size_t     _eden_chunk_capacity;  // ... max entries in array
@@ -950,6 +953,7 @@
 
   // Support for parallel remark of survivor space
   void* get_data_recorder(int thr_num);
+  void sample_eden_chunk();
 
   CMSBitMap* markBitMap()  { return &_markBitMap; }
   void directAllocated(HeapWord* start, size_t size);
@@ -1027,6 +1031,8 @@
 
   // Initialization errors
   bool completed_initialization() { return _completed_initialization; }
+
+  void print_eden_and_survivor_chunk_arrays();
 };
 
 class CMSExpansionCause : public AllStatic  {
@@ -1317,6 +1323,10 @@
     //Delegate to collector
     return collector()->get_data_recorder(thr_num);
   }
+  void sample_eden_chunk() {
+    //Delegate to collector
+    return collector()->sample_eden_chunk();
+  }
 
   // Printing
   const char* name() const;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -96,11 +96,6 @@
           "the buffer will be enqueued for processing. A value of 0 "       \
           "specifies that mutator threads should not do such filtering.")   \
                                                                             \
-  develop(intx, G1ExtraRegionSurvRate, 33,                                  \
-          "If the young survival rate is S, and there's room left in "      \
-          "to-space, we will allow regions whose survival rate is up to "   \
-          "S + (1 - S)*X, where X is this parameter (as a fraction.)")      \
-                                                                            \
   develop(bool, G1SATBPrintStubs, false,                                    \
           "If true, print generated stubs for the SATB barrier")            \
                                                                             \
@@ -110,9 +105,6 @@
   develop(bool, G1RSBarrierRegionFilter, true,                              \
           "If true, generate region filtering code in RS barrier")          \
                                                                             \
-  develop(bool, G1RSBarrierNullFilter, true,                                \
-          "If true, generate null-pointer filtering code in RS barrier")    \
-                                                                            \
   develop(bool, G1DeferredRSUpdate, true,                                   \
           "If true, use deferred RS updates")                               \
                                                                             \
@@ -120,9 +112,6 @@
           "If true, verify that no dirty cards remain after RS log "        \
           "processing.")                                                    \
                                                                             \
-  develop(bool, G1RSCountHisto, false,                                      \
-          "If true, print a histogram of RS occupancies after each pause")  \
-                                                                            \
   diagnostic(bool, G1PrintRegionLivenessInfo, false,                        \
             "Prints the liveness information for all regions in the heap "  \
             "at the end of a marking cycle.")                               \
@@ -169,9 +158,6 @@
   product(uintx, G1ConcRSHotCardLimit, 4,                                   \
           "The threshold that defines (>=) a hot card.")                    \
                                                                             \
-  develop(bool, G1PrintOopAppls, false,                                     \
-          "When true, print applications of closures to external locs.")    \
-                                                                            \
   develop(intx, G1RSetRegionEntriesBase, 256,                               \
           "Max number of regions in a fine-grain table per MB.")            \
                                                                             \
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -314,6 +314,11 @@
     region_size = MAX_REGION_SIZE;
   }
 
+  if (region_size != G1HeapRegionSize) {
+    // Update the flag to make sure that PrintFlagsFinal logs the correct value
+    FLAG_SET_ERGO(uintx, G1HeapRegionSize, region_size);
+  }
+
   // And recalculate the log.
   region_size_log = log2_long((jlong) region_size);
 
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -1033,6 +1033,9 @@
   // have to use it here, as well.
   HeapWord* result = eden()->par_allocate(word_size);
   if (result != NULL) {
+    if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+      _next_gen->sample_eden_chunk();
+    }
     return result;
   }
   do {
@@ -1063,13 +1066,19 @@
   // circular dependency at compile time.
   if (result == NULL) {
     result = allocate_from_space(word_size);
+  } else if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+    _next_gen->sample_eden_chunk();
   }
   return result;
 }
 
 HeapWord* DefNewGeneration::par_allocate(size_t word_size,
                                          bool is_tlab) {
-  return eden()->par_allocate(word_size);
+  HeapWord* res = eden()->par_allocate(word_size);
+  if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+    _next_gen->sample_eden_chunk();
+  }
+  return res;
 }
 
 void DefNewGeneration::gc_prologue(bool full) {
--- a/hotspot/src/share/vm/memory/generation.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/memory/generation.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -455,6 +455,7 @@
   // expected to be GC worker thread-local, with the worker index
   // indicated by "thr_num".
   virtual void* get_data_recorder(int thr_num) { return NULL; }
+  virtual void sample_eden_chunk() {}
 
   // Some generations may require some cleanup actions before allowing
   // a verification.
--- a/hotspot/src/share/vm/memory/metaspace.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/memory/metaspace.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -2254,10 +2254,11 @@
 
 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
   assert_lock_strong(_lock);
+  size_t raw_word_size = get_raw_word_size(word_size);
   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
-  assert(word_size >= min_size,
+  assert(raw_word_size >= min_size,
     err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
-  block_freelists()->return_block(p, word_size);
+  block_freelists()->return_block(p, raw_word_size);
 }
 
 // Adds a chunk to the list of chunks in use.
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -65,7 +65,8 @@
   }
   _sh = this;  // ch is static, should be set only once.
   if ((UseParNewGC ||
-      (UseConcMarkSweepGC && CMSParallelRemarkEnabled) ||
+      (UseConcMarkSweepGC && (CMSParallelInitialMarkEnabled ||
+                              CMSParallelRemarkEnabled)) ||
        UseG1GC) &&
       ParallelGCThreads > 0) {
     _workers = new FlexibleWorkGang("Parallel GC Threads", ParallelGCThreads,
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -1891,6 +1891,10 @@
     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
             "and will likely be removed in future release");
   }
+  if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
+    warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
+        "Use MaxRAMFraction instead.");
+  }
 }
 
 // Check stack pages settings
--- a/hotspot/src/share/vm/runtime/globals.hpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Tue Aug 06 17:01:05 2013 -0700
@@ -1689,6 +1689,9 @@
   product(bool, CMSAbortSemantics, false,                                   \
           "Whether abort-on-overflow semantics is implemented")             \
                                                                             \
+  product(bool, CMSParallelInitialMarkEnabled, true,                        \
+          "Use the parallel initial mark.")                                 \
+                                                                            \
   product(bool, CMSParallelRemarkEnabled, true,                             \
           "Whether parallel remark enabled (only if ParNewGC)")             \
                                                                             \
@@ -1700,6 +1703,14 @@
           "Whether to always record survivor space PLAB bdries"             \
           " (effective only if CMSParallelSurvivorRemarkEnabled)")          \
                                                                             \
+  product(bool, CMSEdenChunksRecordAlways, true,                            \
+          "Whether to always record eden chunks used for "                  \
+          "the parallel initial mark or remark of eden" )                   \
+                                                                            \
+  product(bool, CMSPrintEdenSurvivorChunks, false,                          \
+          "Print the eden and the survivor chunks used for the parallel "   \
+          "initial mark or remark of the eden/survivor spaces")             \
+                                                                            \
   product(bool, CMSConcurrentMTEnabled, true,                               \
           "Whether multi-threaded concurrent work enabled (if ParNewGC)")   \
                                                                             \
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/arguments/TestG1HeapRegionSize.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2013, 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 TestG1HeapRegionSize
+ * @key gc
+ * @bug 8021879
+ * @summary Verify that the flag G1HeapRegionSize is updated properly
+ * @run main/othervm -Xmx64m TestG1HeapRegionSize 1048576
+ * @run main/othervm -XX:G1HeapRegionSize=2m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=3m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=64m -Xmx256m TestG1HeapRegionSize 33554432
+ */
+
+import sun.management.ManagementFactoryHelper;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+
+public class TestG1HeapRegionSize {
+
+  public static void main(String[] args) {
+    HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
+
+    VMOption option = diagnostic.getVMOption("UseG1GC");
+    if (option.getValue().equals("false")) {
+      System.out.println("Skipping this test. It is only a G1 test.");
+      return;
+    }
+
+    String expectedValue = getExpectedValue(args);
+    option = diagnostic.getVMOption("G1HeapRegionSize");
+    if (!expectedValue.equals(option.getValue())) {
+      throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
+    }
+  }
+
+  private static String getExpectedValue(String[] args) {
+    if (args.length != 1) {
+      throw new RuntimeException("Wrong number of arguments. Expected 1 but got " + args.length);
+    }
+    return args[0];
+  }
+
+}
--- a/hotspot/test/gc/g1/TestPrintRegionRememberedSetInfo.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/test/gc/g1/TestPrintRegionRememberedSetInfo.java	Tue Aug 06 17:01:05 2013 -0700
@@ -27,7 +27,7 @@
  * @bug 8014240
  * @summary Test output of G1PrintRegionRememberedSetInfo
  * @library /testlibrary
- * @build TestPrintRegionRememberedSetInfo
+ * @run main TestPrintRegionRememberedSetInfo
  * @author thomas.schatzl@oracle.com
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/startup_warnings/TestDefaultMaxRAMFraction.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2013, 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 TestDefaultMaxRAMFraction
+* @key gc
+* @bug 8021967
+* @summary Test that the deprecated TestDefaultMaxRAMFraction flag print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestDefaultMaxRAMFraction {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:DefaultMaxRAMFraction=4", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. Use MaxRAMFraction instead.");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- a/hotspot/test/runtime/6929067/Test6929067.sh	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/test/runtime/6929067/Test6929067.sh	Tue Aug 06 17:01:05 2013 -0700
@@ -3,6 +3,7 @@
 ##
 ## @test Test6929067.sh
 ## @bug 6929067
+## @bug 8021296
 ## @summary Stack guard pages should be removed when thread is detached
 ## @compile T.java
 ## @run shell Test6929067.sh
@@ -21,6 +22,11 @@
 OS=`uname -s`
 case "$OS" in
   Linux)
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
     NULL=/dev/null
     PS=":"
     FS="/"
@@ -119,10 +125,10 @@
 # Check to ensure you have a /usr/lib/libpthread.so if you don't please look
 # for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation.
 
-gcc -DLINUX ${COMP_FLAG} -o invoke \
-  -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
-  -L${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE} \
-  -ljvm -lpthread invoke.c
+$gcc_cmd -DLINUX ${COMP_FLAG} -o invoke \
+    -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
+    -L${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE} \
+    -ljvm -lpthread invoke.c
 
 ./invoke
 exit $?
--- a/hotspot/test/runtime/7107135/Test7107135.sh	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/test/runtime/7107135/Test7107135.sh	Tue Aug 06 17:01:05 2013 -0700
@@ -27,6 +27,7 @@
 ##
 ## @test Test7107135.sh
 ## @bug 7107135
+## @bug 8021296
 ## @summary Stack guard pages lost after loading library with executable stack.
 ## @run shell Test7107135.sh
 ##
@@ -45,6 +46,11 @@
 case "$OS" in
   Linux)
     echo "Testing on Linux"
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
     ;;
   *)
     NULL=NUL
@@ -62,7 +68,10 @@
 cp ${TESTSRC}${FS}*.java ${THIS_DIR}
 ${TESTJAVA}${FS}bin${FS}javac *.java
 
-gcc -fPIC -shared -c -o test.o -I${TESTJAVA}${FS}include -I${TESTJAVA}${FS}include${FS}linux ${TESTSRC}${FS}test.c
+$gcc_cmd -fPIC -shared -c -o test.o \
+    -I${TESTJAVA}${FS}include -I${TESTJAVA}${FS}include${FS}linux \
+    ${TESTSRC}${FS}test.c
+
 ld -shared -z   execstack -o libtest-rwx.so test.o
 ld -shared -z noexecstack -o libtest-rw.so  test.o
 
--- a/hotspot/test/runtime/jsig/Test8017498.sh	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/test/runtime/jsig/Test8017498.sh	Tue Aug 06 17:01:05 2013 -0700
@@ -27,6 +27,7 @@
 ## @test Test8017498.sh
 ## @bug 8017498
 ## @bug 8020791
+## @bug 8021296
 ## @summary sigaction(sig) results in process hang/timed-out if sig is much greater than SIGRTMAX
 ## @run shell/timeout=30 Test8017498.sh
 ##
@@ -45,6 +46,11 @@
 case "$OS" in
   Linux)
     echo "Testing on Linux"
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
     if [ "$VM_BITS" = "64" ]
     then
         MY_LD_PRELOAD=${TESTJAVA}${FS}jre${FS}lib${FS}amd64${FS}libjsig.so
@@ -64,15 +70,11 @@
 cp ${TESTSRC}${FS}*.java ${THIS_DIR}
 ${TESTJAVA}${FS}bin${FS}javac *.java
 
-gcc -DLINUX -fPIC -shared \
+$gcc_cmd -DLINUX -fPIC -shared \
     -o ${TESTSRC}${FS}libTestJNI.so \
     -I${TESTJAVA}${FS}include \
     -I${TESTJAVA}${FS}include${FS}linux \
     ${TESTSRC}${FS}TestJNI.c
-if [ $? != 0 ]
-then
-    echo "WARNING: the gcc command failed." 2>&1
-fi
 
 # run the java test in the background
 cmd="LD_PRELOAD=$MY_LD_PRELOAD \
--- a/hotspot/test/runtime/jsig/TestJNI.c	Fri Jun 28 16:26:54 2013 -0400
+++ b/hotspot/test/runtime/jsig/TestJNI.c	Tue Aug 06 17:01:05 2013 -0700
@@ -21,7 +21,6 @@
  * questions.
  */
 
-#define _GNU_SOURCE // for the definition of REG_RIP in ucontext.h
 #include <stdio.h>
 #include <jni.h>
 #include <signal.h>
@@ -32,11 +31,8 @@
 #endif
 
 void sig_handler(int sig, siginfo_t *info, ucontext_t *context) {
-    int thrNum;
 
     printf( " HANDLER (1) " );
-    // Move forward RIP to skip failing instruction
-    context->uc_mcontext.gregs[REG_RIP] += 6;
 }
 
 JNIEXPORT void JNICALL Java_TestJNI_doSomething(JNIEnv *env, jclass klass, jint val) {
--- a/jaxp/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/jaxp/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 15e5bb51bc0cd89304dc2f7f29b4c8002e632353 jdk8-b98
 adf49c3ef83c160d53ece623049b2cdccaf78fc7 jdk8-b99
 5d1974c1d7b9a86431bc253dc5a6a52d4586622e jdk8-b100
+0a7432f898e579ea35e8c51e3edab37f949168e4 jdk8-b101
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java	Tue Aug 06 17:01:05 2013 -0700
@@ -112,7 +112,7 @@
     /** Initial EntityResolver */
     private final EntityResolver fInitEntityResolver;
 
-    private XMLSecurityPropertyManager fSecurityPropertyMgr;
+    private final XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     /**
      * Create a SAX parser with the associated features
@@ -130,8 +130,10 @@
     SAXParserImpl(SAXParserFactoryImpl spf, Hashtable features, boolean secureProcessing)
         throws SAXException
     {
+        fSecurityPropertyMgr = new XMLSecurityPropertyManager();
+
         // Instantiate a SAXParser directly and not through SAX so that we use the right ClassLoader
-        xmlReader = new JAXPSAXParser(this);
+        xmlReader = new JAXPSAXParser(this, fSecurityPropertyMgr);
 
         // JAXP "namespaceAware" == SAX Namespaces feature
         // Note: there is a compatibility problem here with default values:
@@ -150,7 +152,6 @@
             xmlReader.setFeature0(XINCLUDE_FEATURE, true);
         }
 
-        fSecurityPropertyMgr = new XMLSecurityPropertyManager();
         xmlReader.setProperty0(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
 
         // If the secure processing feature is on set a security manager.
@@ -397,14 +398,30 @@
         private final HashMap fInitFeatures = new HashMap();
         private final HashMap fInitProperties = new HashMap();
         private final SAXParserImpl fSAXParser;
+        private XMLSecurityPropertyManager fSecurityPropertyMgr;
+
 
         public JAXPSAXParser() {
-            this(null);
+            this(null, null);
         }
 
-        JAXPSAXParser(SAXParserImpl saxParser) {
+        JAXPSAXParser(SAXParserImpl saxParser, XMLSecurityPropertyManager spm) {
             super();
             fSAXParser = saxParser;
+            fSecurityPropertyMgr = spm;
+
+            /**
+             * This class may be used directly. So initialize the security manager if
+             * it is null.
+             */
+            if (fSecurityPropertyMgr == null) {
+                fSecurityPropertyMgr = new XMLSecurityPropertyManager();
+                try {
+                    super.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
+                } catch (Exception ex) {
+                    //shall not happen
+                }
+            }
         }
 
         /**
@@ -542,9 +559,9 @@
                 setSchemaValidatorProperty(name, value);
             }
             /** Check to see if the property is managed by the property manager **/
-            int index = fSAXParser.fSecurityPropertyMgr.getIndex(name);
+            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
             if (index > -1) {
-                fSAXParser.fSecurityPropertyMgr.setValue(index,
+                fSecurityPropertyMgr.setValue(index,
                         XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
             } else {
                 if (!fInitProperties.containsKey(name)) {
@@ -564,9 +581,9 @@
                 // JAXP 1.2 support
                 return fSAXParser.schemaLanguage;
             }
-            int index = fSAXParser.fSecurityPropertyMgr.getIndex(name);
+            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
             if (index > -1) {
-                return fSAXParser.fSecurityPropertyMgr.getValueByIndex(index);
+                return fSecurityPropertyMgr.getValueByIndex(index);
             }
 
             return super.getProperty(name);
--- a/jaxws/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/jaxws/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 b1fb4612a2caea52b5661b87509e560fa044b194 jdk8-b98
 8ef83d4b23c933935e28f59b282cea920b1b1f5f jdk8-b99
 4fd722afae5c02f00bbd44c3a34425ee474afb1c jdk8-b100
+60b623a361642a0f5aef5f06dad9e5f279b9d9a9 jdk8-b101
--- a/jdk/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98
 6a099a36589bd933957272ba63e5263bede29971 jdk8-b99
 5be9c5bfcfe9b2a40412b4fb364377d49de014eb jdk8-b100
+6901612328239fbd471d20823113c1cf3fdaebee jdk8-b101
--- a/jdk/src/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Tue Aug 06 17:01:05 2013 -0700
@@ -31,6 +31,7 @@
 import javax.swing.*;
 import javax.swing.plaf.MenuBarUI;
 
+import com.apple.laf.ScreenMenuBar;
 import sun.lwawt.macosx.CMenuBar;
 
 import com.apple.laf.AquaMenuBarUI;
@@ -72,12 +73,15 @@
         // scan the current frames, and see if any are foreground
         final Frame[] frames = Frame.getFrames();
         for (final Frame frame : frames) {
-            if (frame.isVisible() && !isFrameMinimized(frame)) return;
+            if (frame.isVisible() && !isFrameMinimized(frame)) {
+                return;
+            }
         }
 
         // if we have no foreground frames, then we have to "kick" the menubar
         final JFrame pingFrame = new JFrame();
         pingFrame.getRootPane().putClientProperty("Window.alpha", new Float(0.0f));
+        pingFrame.setUndecorated(true);
         pingFrame.setVisible(true);
         pingFrame.toFront();
         pingFrame.setVisible(false);
@@ -101,7 +105,6 @@
             // Aqua was not installed
             throw new IllegalStateException("Application.setDefaultMenuBar() only works with the Aqua Look and Feel");
         }
-/* TODO: disabled until ScreenMenuBar is working
 
         final AquaMenuBarUI aquaUI = (AquaMenuBarUI)ui;
         final ScreenMenuBar screenMenuBar = aquaUI.getScreenMenuBar();
@@ -118,8 +121,7 @@
         }
 
         // grab the pointer to the CMenuBar, and retain it in native
-        nativeSetDefaultMenuBar(((CMenuBar)peer).getNativeMenuBarPeer());
-*/
+        nativeSetDefaultMenuBar(((CMenuBar)peer).getModel());
     }
 
     void setAboutMenuItemVisible(final boolean present) {
--- a/jdk/src/macosx/classes/sun/font/CStrike.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/classes/sun/font/CStrike.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, 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
@@ -31,7 +31,7 @@
 
 import sun.awt.SunHints;
 
-public class CStrike extends FontStrike {
+public final class CStrike extends FontStrike {
 
     // Creates the native strike
     private static native long createNativeStrikePtr(long nativeFontPtr,
@@ -68,10 +68,10 @@
                                                          Rectangle2D.Float result,
                                                          double x, double y);
 
-    private CFont nativeFont;
+    private final CFont nativeFont;
     private AffineTransform invDevTx;
-    private GlyphInfoCache glyphInfoCache;
-    private GlyphAdvanceCache glyphAdvanceCache;
+    private final GlyphInfoCache glyphInfoCache;
+    private final GlyphAdvanceCache glyphAdvanceCache;
     private long nativeStrikePtr;
 
     CStrike(final CFont font, final FontStrikeDesc inDesc) {
@@ -84,11 +84,11 @@
         // Normally the device transform should be the identity transform
         // for screen operations.  The device transform only becomes
         // interesting when we are outputting between different dpi surfaces,
-        // like when we are printing to postscript.
+        // like when we are printing to postscript or use retina.
         if (inDesc.devTx != null && !inDesc.devTx.isIdentity()) {
             try {
                 invDevTx = inDesc.devTx.createInverse();
-            } catch (NoninvertibleTransformException e) {
+            } catch (NoninvertibleTransformException ignored) {
                 // ignored, since device transforms should not be that
                 // complicated, and if they are - there is nothing we can do,
                 // so we won't worry about it.
@@ -134,15 +134,13 @@
         nativeStrikePtr = 0;
     }
 
-    // the fractional metrics default on our platform is OFF
-    private boolean useFractionalMetrics() {
-        return desc.fmHint == SunHints.INTVAL_FRACTIONALMETRICS_ON;
-    }
 
+    @Override
     public int getNumGlyphs() {
         return nativeFont.getNumGlyphs();
     }
 
+    @Override
     StrikeMetrics getFontMetrics() {
         if (strikeMetrics == null) {
             StrikeMetrics metrics = getFontMetrics(getNativeStrikePtr());
@@ -155,74 +153,24 @@
         return strikeMetrics;
     }
 
-    float getGlyphAdvance(int glyphCode) {
-        return getScaledAdvanceForAdvance(getCachedNativeGlyphAdvance(glyphCode));
+    @Override
+    float getGlyphAdvance(final int glyphCode) {
+        return getCachedNativeGlyphAdvance(glyphCode);
     }
 
-    float getCodePointAdvance(int cp) {
-        float advance = getCachedNativeGlyphAdvance(nativeFont.getMapper().charToGlyph(cp));
-
-        double glyphScaleX = desc.glyphTx.getScaleX();
-        double devScaleX = desc.devTx.getScaleX();
-
-        if (devScaleX == 0) {
-            glyphScaleX = Math.sqrt(desc.glyphTx.getDeterminant());
-            devScaleX = Math.sqrt(desc.devTx.getDeterminant());
-        }
-
-        if (devScaleX == 0) {
-            devScaleX = Double.NaN; // this an undefined graphics state
-        }
-        advance = (float) (advance * glyphScaleX / devScaleX);
-        return useFractionalMetrics() ? advance : Math.round(advance);
+    @Override
+    float getCodePointAdvance(final int cp) {
+        return getGlyphAdvance(nativeFont.getMapper().charToGlyph(cp));
     }
 
-    // calculate an advance, and round if not using fractional metrics
-    private float getScaledAdvanceForAdvance(float advance) {
-        if (invDevTx != null) {
-            advance *= invDevTx.getScaleX();
-        }
-        advance *= desc.glyphTx.getScaleX();
-        return useFractionalMetrics() ? advance : Math.round(advance);
+    @Override
+    Point2D.Float getCharMetrics(final char ch) {
+        return getGlyphMetrics(nativeFont.getMapper().charToGlyph(ch));
     }
 
-    Point2D.Float getCharMetrics(char ch) {
-        return getScaledPointForAdvance(getCachedNativeGlyphAdvance(nativeFont.getMapper().charToGlyph(ch)));
-    }
-
-    Point2D.Float getGlyphMetrics(int glyphCode) {
-        return getScaledPointForAdvance(getCachedNativeGlyphAdvance(glyphCode));
-    }
-
-    // calculate an advance point, and round if not using fractional metrics
-    private Point2D.Float getScaledPointForAdvance(float advance) {
-        Point2D.Float pt = new Point2D.Float(advance, 0);
-
-        if (!desc.glyphTx.isIdentity()) {
-            return scalePoint(pt);
-        }
-
-        if (!useFractionalMetrics()) {
-            pt.x = Math.round(pt.x);
-        }
-        return pt;
-    }
-
-    private Point2D.Float scalePoint(Point2D.Float pt) {
-        if (invDevTx != null) {
-            // transform the point out of the device space first
-            invDevTx.transform(pt, pt);
-        }
-        desc.glyphTx.transform(pt, pt);
-        pt.x -= desc.glyphTx.getTranslateX();
-        pt.y -= desc.glyphTx.getTranslateY();
-
-        if (!useFractionalMetrics()) {
-            pt.x = Math.round(pt.x);
-            pt.y = Math.round(pt.y);
-        }
-
-        return pt;
+    @Override
+    Point2D.Float getGlyphMetrics(final int glyphCode) {
+        return new Point2D.Float(getGlyphAdvance(glyphCode), 0.0f);
     }
 
     Rectangle2D.Float getGlyphOutlineBounds(int glyphCode) {
@@ -414,9 +362,7 @@
         private SparseBitShiftingTwoLayerArray secondLayerCache;
         private HashMap<Integer, Long> generalCache;
 
-        public GlyphInfoCache(final Font2D nativeFont,
-                              final FontStrikeDesc desc)
-        {
+        GlyphInfoCache(final Font2D nativeFont, final FontStrikeDesc desc) {
             super(nativeFont, desc);
             firstLayerCache = new long[FIRST_LAYER_SIZE];
         }
@@ -527,7 +473,7 @@
             final int shift;
             final int secondLayerLength;
 
-            public SparseBitShiftingTwoLayerArray(final int size, final int shift) {
+            SparseBitShiftingTwoLayerArray(final int size, final int shift) {
                 this.shift = shift;
                 this.cache = new long[1 << shift][];
                 this.secondLayerLength = size >> shift;
@@ -559,6 +505,12 @@
         private SparseBitShiftingTwoLayerArray secondLayerCache;
         private HashMap<Integer, Float> generalCache;
 
+        // Empty non private constructor was added because access to this
+        // class shouldn't be emulated by a synthetic accessor method.
+        GlyphAdvanceCache() {
+            super();
+        }
+
         public synchronized float get(final int index) {
             if (index < 0) {
                 if (-index < SECOND_LAYER_SIZE) {
@@ -609,9 +561,7 @@
             final int shift;
             final int secondLayerLength;
 
-            public SparseBitShiftingTwoLayerArray(final int size,
-                                                  final int shift)
-            {
+            SparseBitShiftingTwoLayerArray(final int size, final int shift) {
                 this.shift = shift;
                 this.cache = new float[1 << shift][];
                 this.secondLayerLength = size >> shift;
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Tue Aug 06 17:01:05 2013 -0700
@@ -182,7 +182,11 @@
         Long format = predefinedClipboardNameMap.get(str);
 
         if (format == null) {
-            format = new Long(registerFormatWithPasteboard(str));
+            if (java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance()) {
+                // Do not try to access native system for the unknown format
+                return -1L;
+            }
+            format = registerFormatWithPasteboard(str);
             predefinedClipboardNameMap.put(str, format);
             predefinedClipboardFormatMap.put(format, str);
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CMenuComponent.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CMenuComponent.java	Tue Aug 06 17:01:05 2013 -0700
@@ -43,7 +43,7 @@
         return target;
     }
 
-    long getModel() {
+    public long getModel() {
         return modelPtr;
     }
 
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Tue Aug 06 17:01:05 2013 -0700
@@ -47,7 +47,7 @@
 import com.sun.awt.AWTUtilities;
 
 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
-    private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
+    private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h);
     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
@@ -230,7 +230,8 @@
         contentView = createContentView();
         contentView.initialize(peer, responder);
 
-        final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
+        final long ownerPtr = owner != null ? owner.getNSWindowPtr() : 0L;
+        final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), ownerPtr, styleBits, 0, 0, 0, 0);
         setPtr(nativeWindowPtr);
 
         if (target instanceof javax.swing.RootPaneContainer) {
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.h	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.h	Tue Aug 06 17:01:05 2013 -0700
@@ -44,6 +44,7 @@
     jint styleBits;
     BOOL isEnabled;
     NSWindow *nsWindow;
+    AWTWindow *ownerWindow;
 }
 
 // An instance of either AWTWindow_Normal or AWTWindow_Panel
@@ -51,12 +52,15 @@
 
 @property (nonatomic, retain) JNFWeakJObjectWrapper *javaPlatformWindow;
 @property (nonatomic, retain) CMenuBar *javaMenuBar;
+@property (nonatomic, retain) AWTWindow *ownerWindow;
 @property (nonatomic) NSSize javaMinSize;
 @property (nonatomic) NSSize javaMaxSize;
 @property (nonatomic) jint styleBits;
 @property (nonatomic) BOOL isEnabled;
 
+
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)javaPlatformWindow
+                  ownerWindow:owner
                     styleBits:(jint)styleBits
                     frameRect:(NSRect)frameRect
                   contentView:(NSView *)contentView;
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.m	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m	Tue Aug 06 17:01:05 2013 -0700
@@ -30,6 +30,7 @@
 #import "sun_lwawt_macosx_CPlatformWindow.h"
 #import "com_apple_eawt_event_GestureHandler.h"
 #import "com_apple_eawt_FullScreenHandler.h"
+#import "ApplicationDelegate.h"
 
 #import "AWTWindow.h"
 #import "AWTView.h"
@@ -55,7 +56,7 @@
 // doesn't provide information about "opposite" window, so we
 // have to do a bit of tracking. This variable points to a window
 // which had been the key window just before a new key window
-// was set. It would be nil if the new key window isn't an AWT 
+// was set. It would be nil if the new key window isn't an AWT
 // window or the app currently has no key window.
 static AWTWindow* lastKeyWindow = nil;
 
@@ -120,6 +121,7 @@
 @synthesize javaMaxSize;
 @synthesize styleBits;
 @synthesize isEnabled;
+@synthesize ownerWindow;
 
 - (void) updateMinMaxSize:(BOOL)resizable {
     if (resizable) {
@@ -201,6 +203,7 @@
 }
 
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)platformWindow
+                  ownerWindow:owner
                     styleBits:(jint)bits
                     frameRect:(NSRect)rect
                   contentView:(NSView *)view
@@ -245,6 +248,7 @@
     self.isEnabled = YES;
     self.javaPlatformWindow = platformWindow;
     self.styleBits = bits;
+    self.ownerWindow = owner;
     [self setPropertiesForStyleBits:styleBits mask:MASK(_METHOD_PROP_BITMASK)];
 
     return self;
@@ -350,7 +354,7 @@
     [self.javaPlatformWindow setJObject:nil withEnv:env];
 
     self.nsWindow = nil;
-
+    self.ownerWindow = nil;
     [super dealloc];
 }
 
@@ -539,11 +543,27 @@
 AWT_ASSERT_APPKIT_THREAD;
     [AWTToolkit eventCountPlusPlus];
     AWTWindow *opposite = [AWTWindow lastKeyWindow];
-    if (!IS(self.styleBits, IS_DIALOG)) {
-        [CMenuBar activate:self.javaMenuBar modallyDisabled:NO];
-    } else if ((opposite != NULL) && IS(self.styleBits, IS_MODAL)) {
-        [CMenuBar activate:opposite->javaMenuBar modallyDisabled:YES];        
+
+    // Finds appropriate menubar in our hierarchy,
+    AWTWindow *awtWindow = self;
+    while (awtWindow.ownerWindow != nil) {
+        awtWindow = awtWindow.ownerWindow;
     }
+
+    CMenuBar *menuBar = nil;
+    BOOL isDisabled = NO;
+    if ([awtWindow.nsWindow isVisible]){
+        menuBar = awtWindow.javaMenuBar;
+        isDisabled = !awtWindow.isEnabled;
+    }
+
+    if (menuBar == nil) {
+        menuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+        isDisabled = NO;
+    }
+
+    [CMenuBar activate:menuBar modallyDisabled:isDisabled];
+
     [AWTWindow setLastKeyWindow:nil];
 
     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
@@ -555,6 +575,14 @@
     [AWTToolkit eventCountPlusPlus];
     [self.javaMenuBar deactivate];
 
+    // In theory, this might cause flickering if the window gaining focus
+    // has its own menu. However, I couldn't reproduce it on practice, so
+    // perhaps this is a non issue.
+    CMenuBar* defaultMenu = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+    if (defaultMenu != nil) {
+        [CMenuBar activate:defaultMenu modallyDisabled:NO];
+    }
+
     // the new key window
     NSWindow *keyWindow = [NSApp keyWindow];
     AWTWindow *opposite = nil;
@@ -741,7 +769,7 @@
  * Signature: (JJIIII)J
  */
 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeCreateNSWindow
-(JNIEnv *env, jobject obj, jlong contentViewPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
+(JNIEnv *env, jobject obj, jlong contentViewPtr, jlong ownerPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
 {
     __block AWTWindow *window = nil;
 
@@ -750,13 +778,14 @@
     JNFWeakJObjectWrapper *platformWindow = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
     NSView *contentView = OBJC(contentViewPtr);
     NSRect frameRect = NSMakeRect(x, y, w, h);
-
+    AWTWindow *owner = [OBJC(ownerPtr) delegate];
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 
         window = [[AWTWindow alloc] initWithPlatformWindow:platformWindow
-                                                  styleBits:styleBits
-                                                  frameRect:frameRect
-                                                contentView:contentView];
+                                               ownerWindow:owner
+                                                 styleBits:styleBits
+                                                 frameRect:frameRect
+                                               contentView:contentView];
         // the window is released is CPlatformWindow.nativeDispose()
 
         if (window) CFRetain(window.nsWindow);
@@ -818,11 +847,19 @@
 
         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 
-        if ([nsWindow isKeyWindow]) [window.javaMenuBar deactivate];
+        if ([nsWindow isKeyWindow]) {
+            [window.javaMenuBar deactivate];
+        }
+
         window.javaMenuBar = menuBar;
 
+        CMenuBar* actualMenuBar = menuBar;
+        if (actualMenuBar == nil) {
+            actualMenuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+        }
+
         if ([nsWindow isKeyWindow]) {
-            [CMenuBar activate:window.javaMenuBar modallyDisabled:NO];
+            [CMenuBar activate:actualMenuBar modallyDisabled:NO];
         }
     }];
 
--- a/jdk/src/macosx/native/sun/awt/CMenuBar.m	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/awt/CMenuBar.m	Tue Aug 06 17:01:05 2013 -0700
@@ -63,7 +63,7 @@
         if (excludingAppleMenu && ![currMenu isJavaMenu]) {
             continue;
         }
-
+        [currItem setSubmenu:nil];
         [theMainMenu removeItemAtIndex:index];
     }
 
@@ -154,7 +154,10 @@
     // Clean up extra items
     NSUInteger removedIndex, removedCount = [removedMenuArray count];
     for (removedIndex=removedCount; removedIndex > 0; removedIndex--) {
-        [theMainMenu removeItemAtIndex:[[removedMenuArray objectAtIndex:(removedIndex-1)] integerValue]];
+        NSUInteger index = [[removedMenuArray objectAtIndex:(removedIndex-1)] integerValue];
+        NSMenuItem *currItem = [theMainMenu itemAtIndex:index];
+        [currItem setSubmenu:nil];
+        [theMainMenu removeItemAtIndex:index];
     }
 
     i = cmenuIndex;
--- a/jdk/src/macosx/native/sun/awt/CMenuItem.m	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m	Tue Aug 06 17:01:05 2013 -0700
@@ -70,9 +70,15 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
 JNF_COCOA_ENTER(env);
 
-    // If we are called as a result of user pressing a shorcut, do nothing,
+    // If we are called as a result of user pressing a shortcut, do nothing,
     // because AVTView has already sent corresponding key event to the Java
-    // layer from performKeyEquivalent
+    // layer from performKeyEquivalent.
+    // There is an exception from the rule above, though: if a window with
+    // a menu gets minimized by user and there are no other windows to take
+    // focus, the window's menu won't be removed from the global menu bar.
+    // However, the Java layer won't handle invocation by a shortcut coming
+    // from this "frameless" menu, because there are no active windows. This
+    // means we have to handle it here.
     NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
     if ([currEvent type] == NSKeyDown) {
         NSString *menuKey = [sender keyEquivalent];
@@ -91,7 +97,8 @@
             eventKey = [NSString stringWithCharacters: &newChar length: 1];
         }
 
-        if ([menuKey isEqualToString:eventKey]) {
+        NSWindow *keyWindow = [NSApp keyWindow];
+        if ([menuKey isEqualToString:eventKey] && keyWindow != nil) {
             return;
         }
     }
--- a/jdk/src/macosx/native/sun/font/AWTStrike.h	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/font/AWTStrike.h	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, 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
@@ -31,11 +31,12 @@
 @interface AWTStrike : NSObject {
 @public
     AWTFont *                fAWTFont;
-    CGFloat                    fSize;
+    CGFloat                  fSize;
     JRSFontRenderingStyle    fStyle;
-    jint                    fAAStyle;
+    jint                     fAAStyle;
 
     CGAffineTransform        fTx;
+    CGAffineTransform        fDevTx;
     CGAffineTransform        fAltTx; // alternate strike tx used for Sun2D
     CGAffineTransform        fFontTx;
 }
--- a/jdk/src/macosx/native/sun/font/AWTStrike.m	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/font/AWTStrike.m	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, 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
@@ -65,6 +65,7 @@
         invDevTx.b *= -1;
         invDevTx.c *= -1;
         fFontTx = CGAffineTransformConcat(CGAffineTransformConcat(tx, invDevTx), sInverseTX);
+        fDevTx = CGAffineTransformInvert(invDevTx);
 
         // the "font size" is the square root of the determinant of the matrix
         fSize = sqrt(abs(fFontTx.a * fFontTx.d - fFontTx.b * fFontTx.c));
@@ -148,7 +149,8 @@
 {
     CGSize advance;
 JNF_COCOA_ENTER(env);
-    AWTFont *awtFont = ((AWTStrike *)jlong_to_ptr(awtStrikePtr))->fAWTFont;
+    AWTStrike *awtStrike = (AWTStrike *)jlong_to_ptr(awtStrikePtr);
+    AWTFont *awtFont = awtStrike->fAWTFont;
 
     // negative glyph codes are really unicodes, which were placed there by the mapper
     // to indicate we should use CoreText to substitute the character
@@ -156,6 +158,10 @@
     const CTFontRef fallback = CTS_CopyCTFallbackFontAndGlyphForJavaGlyphCode(awtFont, glyphCode, &glyph);
     CTFontGetAdvancesForGlyphs(fallback, kCTFontDefaultOrientation, &glyph, &advance, 1);
     CFRelease(fallback);
+    advance = CGSizeApplyAffineTransform(advance, awtStrike->fFontTx);
+    if (!JRSFontStyleUsesFractionalMetrics(awtStrike->fStyle)) {
+        advance.width = round(advance.width);
+    }
 
 JNF_COCOA_EXIT(env);
     return advance.width;
--- a/jdk/src/macosx/native/sun/font/CGGlyphImages.m	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/macosx/native/sun/font/CGGlyphImages.m	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, 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
@@ -455,6 +455,7 @@
 #define CGGI_GLYPH_BBOX_PADDING 2.0f
 static inline GlyphInfo *
 CGGI_CreateNewGlyphInfoFrom(CGSize advance, CGRect bbox,
+                            const AWTStrike *strike,
                             const CGGI_RenderingMode *mode)
 {
     size_t pixelSize = mode->glyphDescriptor->pixelSize;
@@ -477,6 +478,12 @@
         width = 1;
         height = 1;
     }
+    advance = CGSizeApplyAffineTransform(advance, strike->fFontTx);
+    if (!JRSFontStyleUsesFractionalMetrics(strike->fStyle)) {
+        advance.width = round(advance.width);
+        advance.height = round(advance.height);
+    }
+    advance = CGSizeApplyAffineTransform(advance, strike->fDevTx);
 
 #ifdef USE_IMAGE_ALIGNED_MEMORY
     // create separate memory
@@ -564,10 +571,10 @@
     JRSFontGetBoundingBoxesForGlyphsAndStyle(fallback, &tx, style, &glyph, 1, &bbox);
 
     CGSize advance;
-    JRSFontGetAdvancesForGlyphsAndStyle(fallback, &tx, strike->fStyle, &glyph, 1, &advance);
+    CTFontGetAdvancesForGlyphs(fallback, kCTFontDefaultOrientation, &glyph, &advance, 1);
 
     // create the Sun2D GlyphInfo we are going to strike into
-    GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
+    GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 
     // fix the context size, just in case the substituted character is unexpectedly large
     CGGI_SizeCanvas(canvas, info->width, info->height, mode->cgFontMode);
@@ -715,7 +722,7 @@
     JRSFontRenderingStyle bboxCGMode = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 
     JRSFontGetBoundingBoxesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, bboxCGMode, glyphs, len, bboxes);
-    JRSFontGetAdvancesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, strike->fStyle, glyphs, len, advances);
+    CTFontGetAdvancesForGlyphs((CTFontRef)font->fFont, kCTFontDefaultOrientation, glyphs, advances, len);
 
     size_t maxWidth = 1;
     size_t maxHeight = 1;
@@ -732,7 +739,7 @@
         CGSize advance = advances[i];
         CGRect bbox = bboxes[i];
 
-        GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
+        GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 
         if (maxWidth < glyphInfo->width)   maxWidth = glyphInfo->width;
         if (maxHeight < glyphInfo->height) maxHeight = glyphInfo->height;
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk.properties	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -1,54 +1,54 @@
-# Refer to the note in basic.properties for a description as to what
-# the mnemonics correspond to and how to calculate them.
-
-
-
-# GTK specific properties
-
-# GTK color chooser properties:
-GTKColorChooserPanel.textAndMnemonic=&GTK Color Chooser
-# mnemonic as a VK_ constant
-
-GTKColorChooserPanel.hue.textAndMnemonic=&Hue:
-
-GTKColorChooserPanel.red.textAndMnemonic=R&ed:
-
-GTKColorChooserPanel.saturation.textAndMnemonic=&Saturation:
-
-GTKColorChooserPanel.green.textAndMnemonic=&Green:
-
-GTKColorChooserPanel.value.textAndMnemonic=&Value:
-
-GTKColorChooserPanel.blue.textAndMnemonic=&Blue:
-
-GTKColorChooserPanel.color.textAndMnemonic=Color &Name:
-
-
-
-############ FILE CHOOSER STRINGS #############
-
-FileChooser.acceptAllFileFilter.textAndMnemonic=All Files
-FileChooser.newFolderButton.textAndMnemonic=&New Folder
-FileChooser.newFolderDialog.textAndMnemonic=Folder name:
-FileChooser.newFolderNoDirectoryErrorTitle.textAndMnemonic=Error
-FileChooser.newFolderNoDirectoryError.textAndMnemonic=Error creating directory "{0}": No such file or directory
-FileChooser.deleteFileButton.textAndMnemonic=De&lete File
-FileChooser.renameFileButton.textAndMnemonic=&Rename File
-FileChooser.cancelButton.textAndMnemonic=&Cancel
-FileChooser.saveButton.textAndMnemonic=&OK
-FileChooser.openButton.textAndMnemonic=&OK
-FileChooser.saveDialogTitle.textAndMnemonic=Save
-FileChooser.openDialogTitle.textAndMnemonic=Open
-FileChooser.pathLabel.textAndMnemonic=&Selection:
-FileChooser.filterLabel.textAndMnemonic=Filter:
-FileChooser.foldersLabel.textAndMnemonic=Fol&ders
-FileChooser.filesLabel.textAndMnemonic=&Files
-
-FileChooser.cancelButtonToolTip.textAndMnemonic=Abort file chooser dialog.
-FileChooser.saveButtonToolTip.textAndMnemonic=Save selected file.
-FileChooser.openButtonToolTip.textAndMnemonic=Open selected file.
-
-FileChooser.renameFileDialog.textAndMnemonic=Rename file "{0}" to
-FileChooser.renameFileError.titleAndMnemonic=Error
-FileChooser.renameFileError.textAndMnemonic=Error renaming file "{0}" to "{1}"
-
+# Refer to the note in basic.properties for a description as to what
+# the mnemonics correspond to and how to calculate them.
+
+
+
+# GTK specific properties
+
+# GTK color chooser properties:
+GTKColorChooserPanel.textAndMnemonic=&GTK Color Chooser
+# mnemonic as a VK_ constant
+
+GTKColorChooserPanel.hue.textAndMnemonic=&Hue:
+
+GTKColorChooserPanel.red.textAndMnemonic=R&ed:
+
+GTKColorChooserPanel.saturation.textAndMnemonic=&Saturation:
+
+GTKColorChooserPanel.green.textAndMnemonic=&Green:
+
+GTKColorChooserPanel.value.textAndMnemonic=&Value:
+
+GTKColorChooserPanel.blue.textAndMnemonic=&Blue:
+
+GTKColorChooserPanel.color.textAndMnemonic=Color &Name:
+
+
+
+############ FILE CHOOSER STRINGS #############
+
+FileChooser.acceptAllFileFilter.textAndMnemonic=All Files
+FileChooser.newFolderButton.textAndMnemonic=&New Folder
+FileChooser.newFolderDialog.textAndMnemonic=Folder name:
+FileChooser.newFolderNoDirectoryErrorTitle.textAndMnemonic=Error
+FileChooser.newFolderNoDirectoryError.textAndMnemonic=Error creating directory "{0}": No such file or directory
+FileChooser.deleteFileButton.textAndMnemonic=De&lete File
+FileChooser.renameFileButton.textAndMnemonic=&Rename File
+FileChooser.cancelButton.textAndMnemonic=&Cancel
+FileChooser.saveButton.textAndMnemonic=&OK
+FileChooser.openButton.textAndMnemonic=&OK
+FileChooser.saveDialogTitle.textAndMnemonic=Save
+FileChooser.openDialogTitle.textAndMnemonic=Open
+FileChooser.pathLabel.textAndMnemonic=&Selection:
+FileChooser.filterLabel.textAndMnemonic=Filter:
+FileChooser.foldersLabel.textAndMnemonic=Fol&ders
+FileChooser.filesLabel.textAndMnemonic=&Files
+
+FileChooser.cancelButtonToolTip.textAndMnemonic=Abort file chooser dialog.
+FileChooser.saveButtonToolTip.textAndMnemonic=Save selected file.
+FileChooser.openButtonToolTip.textAndMnemonic=Open selected file.
+
+FileChooser.renameFileDialog.textAndMnemonic=Rename file "{0}" to
+FileChooser.renameFileError.titleAndMnemonic=Error
+FileChooser.renameFileError.textAndMnemonic=Error renaming file "{0}" to "{1}"
+
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java	Tue Aug 06 17:01:05 2013 -0700
@@ -499,7 +499,8 @@
 
         public void setItem(Object item) {
             super.setItem(item);
-            if (editor.hasFocus()) {
+            Object focus = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
+            if ((focus == editor) || (focus == editor.getParent())) {
                 editor.selectAll();
             }
         }
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/synth/resources/synth.properties	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/synth/resources/synth.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -1,45 +1,45 @@
-# This properties file is used to create a PropertyResourceBundle
-# It contains Locale specific strings used be the Synth Look and Feel.
-# Currently, the following components need this for support:
-#
-#    FileChooser
-#
-# When this file is read in, the strings are put into the
-# defaults table.  This is an implementation detail of the current
-# workings of Swing.  DO NOT DEPEND ON THIS.
-# This may change in future versions of Swing as we improve localization
-# support.
-#
-# Refer to the note in basic.properties for a description as to what
-# the mnemonics correspond to and how to calculate them.
-#
-# @author Steve Wilson
-
-
-############ FILE CHOOSER STRINGS #############
-
-FileChooser.lookInLabel.textAndMnemonic=Look &In:
-FileChooser.saveInLabel.textAndMnemonic=Save In:
-FileChooser.fileNameLabel.textAndMnemonic=File &Name:
-FileChooser.folderNameLabel.textAndMnemonic=Folder &Name:
-FileChooser.filesOfTypeLabel.textAndMnemonic=Files of &Type:
-FileChooser.upFolderToolTip.textAndMnemonic=Up One Level
-FileChooser.upFolderAccessibleName=Up
-FileChooser.homeFolderToolTip.textAndMnemonic=Home
-FileChooser.homeFolderAccessibleName=Home
-FileChooser.newFolderToolTip.textAndMnemonic=Create New Folder
-FileChooser.newFolderAccessibleName=New Folder
-FileChooser.newFolderActionLabel.textAndMnemonic=New Folder
-FileChooser.listViewButtonToolTip.textAndMnemonic=List
-FileChooser.listViewButtonAccessibleName=List
-FileChooser.listViewActionLabel.textAndMnemonic=List
-FileChooser.detailsViewButtonToolTip.textAndMnemonic=Details
-FileChooser.detailsViewButtonAccessibleName=Details
-FileChooser.detailsViewActionLabel.textAndMnemonic=Details
-FileChooser.refreshActionLabel.textAndMnemonic=Refresh
-FileChooser.viewMenuLabel.textAndMnemonic=View
-FileChooser.fileNameHeader.textAndMnemonic=Name
-FileChooser.fileSizeHeader.textAndMnemonic=Size
-FileChooser.fileTypeHeader.textAndMnemonic=Type
-FileChooser.fileDateHeader.textAndMnemonic=Modified
-FileChooser.fileAttrHeader.textAndMnemonic=Attributes
+# This properties file is used to create a PropertyResourceBundle
+# It contains Locale specific strings used be the Synth Look and Feel.
+# Currently, the following components need this for support:
+#
+#    FileChooser
+#
+# When this file is read in, the strings are put into the
+# defaults table.  This is an implementation detail of the current
+# workings of Swing.  DO NOT DEPEND ON THIS.
+# This may change in future versions of Swing as we improve localization
+# support.
+#
+# Refer to the note in basic.properties for a description as to what
+# the mnemonics correspond to and how to calculate them.
+#
+# @author Steve Wilson
+
+
+############ FILE CHOOSER STRINGS #############
+
+FileChooser.lookInLabel.textAndMnemonic=Look &In:
+FileChooser.saveInLabel.textAndMnemonic=Save In:
+FileChooser.fileNameLabel.textAndMnemonic=File &Name:
+FileChooser.folderNameLabel.textAndMnemonic=Folder &Name:
+FileChooser.filesOfTypeLabel.textAndMnemonic=Files of &Type:
+FileChooser.upFolderToolTip.textAndMnemonic=Up One Level
+FileChooser.upFolderAccessibleName=Up
+FileChooser.homeFolderToolTip.textAndMnemonic=Home
+FileChooser.homeFolderAccessibleName=Home
+FileChooser.newFolderToolTip.textAndMnemonic=Create New Folder
+FileChooser.newFolderAccessibleName=New Folder
+FileChooser.newFolderActionLabel.textAndMnemonic=New Folder
+FileChooser.listViewButtonToolTip.textAndMnemonic=List
+FileChooser.listViewButtonAccessibleName=List
+FileChooser.listViewActionLabel.textAndMnemonic=List
+FileChooser.detailsViewButtonToolTip.textAndMnemonic=Details
+FileChooser.detailsViewButtonAccessibleName=Details
+FileChooser.detailsViewActionLabel.textAndMnemonic=Details
+FileChooser.refreshActionLabel.textAndMnemonic=Refresh
+FileChooser.viewMenuLabel.textAndMnemonic=View
+FileChooser.fileNameHeader.textAndMnemonic=Name
+FileChooser.fileSizeHeader.textAndMnemonic=Size
+FileChooser.fileTypeHeader.textAndMnemonic=Type
+FileChooser.fileDateHeader.textAndMnemonic=Modified
+FileChooser.fileAttrHeader.textAndMnemonic=Attributes
--- a/jdk/src/share/classes/java/awt/AWTException.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/java/awt/AWTException.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2013, 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 @@
 
 
 /**
- * Signals that an Absract Window Toolkit exception has occurred.
+ * Signals that an Abstract Window Toolkit exception has occurred.
  *
  * @author      Arthur van Hoff
  */
--- a/jdk/src/share/classes/javax/swing/JFileChooser.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/javax/swing/JFileChooser.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1149,9 +1149,10 @@
         int index = filters.indexOf(f);
         if (index >= 0) {
             if(getFileFilter() == f) {
-                if (isAcceptAllFileFilterUsed()) {
+                FileFilter aaff = getAcceptAllFileFilter();
+                if (isAcceptAllFileFilterUsed() && (aaff != f)) {
                     // choose default filter if it is used
-                    setFileFilter(getAcceptAllFileFilter());
+                    setFileFilter(aaff);
                 }
                 else if (index > 0) {
                     // choose the first filter, because it is not removed
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java	Tue Aug 06 17:01:05 2013 -0700
@@ -344,7 +344,8 @@
             configureRenderer(cellContext);
             while (!done && paintingEnumerator.hasMoreElements()) {
                 path = (TreePath)paintingEnumerator.nextElement();
-                if (path != null) {
+                bounds = getPathBounds(tree, path);
+                if ((path != null) && (bounds != null)) {
                     isLeaf = treeModel.isLeaf(path.getLastPathComponent());
                     if (isLeaf) {
                         isExpanded = hasBeenExpanded = false;
@@ -353,7 +354,6 @@
                         isExpanded = treeState.getExpandedState(path);
                         hasBeenExpanded = tree.hasBeenExpanded(path);
                     }
-                    bounds = getPathBounds(tree, path);
                     rowBounds.y = bounds.y;
                     rowBounds.height = bounds.height;
                     paintRow(renderer, dtcr, context, cellContext, g,
@@ -383,7 +383,8 @@
             paintingEnumerator = treeState.getVisiblePathsFrom(initialPath);
             while (!done && paintingEnumerator.hasMoreElements()) {
                 path = (TreePath)paintingEnumerator.nextElement();
-                if (path != null) {
+                bounds = getPathBounds(tree, path);
+                if ((path != null) && (bounds != null)) {
                     isLeaf = treeModel.isLeaf(path.getLastPathComponent());
                     if (isLeaf) {
                         isExpanded = hasBeenExpanded = false;
@@ -392,7 +393,6 @@
                         isExpanded = treeState.getExpandedState(path);
                         hasBeenExpanded = tree.hasBeenExpanded(path);
                     }
-                    bounds = getPathBounds(tree, path);
                     // See if the vertical line to the parent has been drawn.
                     parentPath = path.getParentPath();
                     if (parentPath != null) {
--- a/jdk/src/share/classes/sun/font/TrueTypeFont.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/sun/font/TrueTypeFont.java	Tue Aug 06 17:01:05 2013 -0700
@@ -547,6 +547,17 @@
                     throw new FontFormatException("bad table, tag="+table.tag);
                 }
             }
+
+            if (getDirectoryEntry(headTag) == null) {
+                throw new FontFormatException("missing head table");
+            }
+            if (getDirectoryEntry(maxpTag) == null) {
+                throw new FontFormatException("missing maxp table");
+            }
+            if (getDirectoryEntry(hmtxTag) != null
+                    && getDirectoryEntry(hheaTag) == null) {
+                throw new FontFormatException("missing hhea table");
+            }
             initNames();
         } catch (Exception e) {
             if (FontUtilities.isLogging()) {
--- a/jdk/src/share/classes/sun/print/PSPrinterJob.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/sun/print/PSPrinterJob.java	Tue Aug 06 17:01:05 2013 -0700
@@ -59,6 +59,8 @@
 import javax.print.StreamPrintService;
 import javax.print.attribute.HashPrintRequestAttributeSet;
 import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.PrintServiceAttributeSet;
+import javax.print.attribute.standard.PrinterName;
 import javax.print.attribute.standard.Chromaticity;
 import javax.print.attribute.standard.Copies;
 import javax.print.attribute.standard.Destination;
@@ -766,8 +768,9 @@
             }
         }
         if (mDestType == RasterPrinterJob.PRINTER) {
-            if (getPrintService() != null) {
-                mDestination = getPrintService().getName();
+            PrintService pServ = getPrintService();
+            if (pServ != null) {
+                mDestination = pServ.getName();
             }
             PrinterSpooler spooler = new PrinterSpooler();
             java.security.AccessController.doPrivileged(spooler);
--- a/jdk/src/share/classes/sun/swing/JLightweightFrame.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/sun/swing/JLightweightFrame.java	Tue Aug 06 17:01:05 2013 -0700
@@ -29,12 +29,18 @@
 import java.awt.Color;
 import java.awt.Component;
 import java.awt.Container;
+import java.awt.Dimension;
 import java.awt.EventQueue;
 import java.awt.Graphics;
 import java.awt.Graphics2D;
 import java.awt.Rectangle;
+import java.awt.event.ComponentListener;
+import java.awt.event.ContainerEvent;
+import java.awt.event.ContainerListener;
 import java.awt.image.BufferedImage;
 import java.awt.image.DataBufferInt;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
 import java.security.AccessController;
 
 import javax.swing.JLayeredPane;
@@ -80,6 +86,8 @@
     private boolean copyBufferEnabled;
     private int[] copyBuffer;
 
+    private PropertyChangeListener layoutSizeListener;
+
     /**
      * Constructs a new, initially invisible {@code JLightweightFrame}
      * instance.
@@ -94,6 +102,23 @@
         if (getGraphicsConfiguration().isTranslucencyCapable()) {
             setBackground(new Color(0, 0, 0, 0));
         }
+
+        layoutSizeListener = new PropertyChangeListener() {
+            @Override
+            public void propertyChange(PropertyChangeEvent e) {
+                Dimension d = (Dimension)e.getNewValue();
+
+                if ("preferredSize".equals(e.getPropertyName())) {
+                    content.preferredSizeChanged(d.width, d.height);
+
+                } else if ("maximumSize".equals(e.getPropertyName())) {
+                    content.maximumSizeChanged(d.width, d.height);
+
+                } else if ("minimumSize".equals(e.getPropertyName())) {
+                    content.minimumSizeChanged(d.width, d.height);
+                }
+            }
+        };
     }
 
     /**
@@ -104,10 +129,23 @@
      *
      * @param content the {@link LightweightContent} instance
      */
-    public void setContent(LightweightContent content) {
+    public void setContent(final LightweightContent content) {
+        if (content == null) {
+            System.err.println("JLightweightFrame.setContent: content may not be null!");
+            return;
+        }
         this.content = content;
         this.component = content.getComponent();
 
+        Dimension d = this.component.getPreferredSize();
+        content.preferredSizeChanged(d.width, d.height);
+
+        d = this.component.getMaximumSize();
+        content.maximumSizeChanged(d.width, d.height);
+
+        d = this.component.getMinimumSize();
+        content.minimumSizeChanged(d.width, d.height);
+
         initInterior();
     }
 
@@ -202,6 +240,25 @@
         contentPane.setLayout(new BorderLayout());
         contentPane.add(component);
         setContentPane(contentPane);
+
+        contentPane.addContainerListener(new ContainerListener() {
+            @Override
+            public void componentAdded(ContainerEvent e) {
+                Component c = JLightweightFrame.this.component;
+                if (e.getChild() == c) {
+                    c.addPropertyChangeListener("preferredSize", layoutSizeListener);
+                    c.addPropertyChangeListener("maximumSize", layoutSizeListener);
+                    c.addPropertyChangeListener("minimumSize", layoutSizeListener);
+                }
+            }
+            @Override
+            public void componentRemoved(ContainerEvent e) {
+                Component c = JLightweightFrame.this.component;
+                if (e.getChild() == c) {
+                    c.removePropertyChangeListener(layoutSizeListener);
+                }
+            }
+        });
     }
 
     @SuppressWarnings("deprecation")
--- a/jdk/src/share/classes/sun/swing/LightweightContent.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/classes/sun/swing/LightweightContent.java	Tue Aug 06 17:01:05 2013 -0700
@@ -161,4 +161,22 @@
      * application that the frame has ungrabbed focus.
      */
     public void focusUngrabbed();
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the content preferred size has changed.
+     */
+    public void preferredSizeChanged(int width, int height);
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the content maximum size has changed.
+     */
+    public void maximumSizeChanged(int width, int height);
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the content minimum size has changed.
+     */
+    public void minimumSizeChanged(int width, int height);
 }
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Tue Aug 06 17:01:05 2013 -0700
@@ -106,7 +106,7 @@
 /******************** StreamBuffer definition ************************/
 
 typedef struct streamBufferStruct {
-    jobject stream;            // ImageInputStream or ImageOutputStream
+    jweak ioRef;               // weak reference to a provider of I/O routines
     jbyteArray hstreamBuffer;  // Handle to a Java buffer for the stream
     JOCTET *buf;               // Pinned buffer pointer */
     size_t bufferOffset;          // holds offset between unpin and the next pin
@@ -125,6 +125,15 @@
  */
 #define STREAMBUF_SIZE 4096
 
+#define GET_IO_REF(io_name)                                            \
+    do {                                                               \
+        if ((*env)->IsSameObject(env, sb->ioRef, NULL) ||              \
+            ((io_name) = (*env)->NewLocalRef(env, sb->ioRef)) == NULL) \
+        {                                                              \
+            cinfo->err->error_exit((j_common_ptr) cinfo);              \
+        }                                                              \
+    } while (0)                                                        \
+
 /*
  * Used to signal that no data need be restored from an unpin to a pin.
  * I.e. the buffer is empty.
@@ -159,7 +168,7 @@
     }
 
 
-    sb->stream = NULL;
+    sb->ioRef = NULL;
 
     sb->buf = NULL;
 
@@ -191,9 +200,9 @@
  * All other state is reset.
  */
 static void resetStreamBuffer(JNIEnv *env, streamBufferPtr sb) {
-    if (sb->stream != NULL) {
-        (*env)->DeleteGlobalRef(env, sb->stream);
-        sb->stream = NULL;
+    if (sb->ioRef != NULL) {
+        (*env)->DeleteWeakGlobalRef(env, sb->ioRef);
+        sb->ioRef = NULL;
     }
     unpinStreamBuffer(env, sb, NULL);
     sb->bufferOffset = NO_DATA;
@@ -571,7 +580,7 @@
 static void imageio_set_stream(JNIEnv *env,
                                j_common_ptr cinfo,
                                imageIODataPtr data,
-                               jobject stream){
+                               jobject io){
     streamBufferPtr sb;
     sun_jpeg_error_ptr jerr;
 
@@ -579,13 +588,13 @@
 
     resetStreamBuffer(env, sb);  // Removes any old stream
 
-    /* Now we need a new global reference for the stream */
-    if (stream != NULL) { // Fix for 4411955
-        sb->stream = (*env)->NewGlobalRef(env, stream);
-        if (sb->stream == NULL) {
+    /* Now we need a new weak global reference for the I/O provider */
+    if (io != NULL) { // Fix for 4411955
+        sb->ioRef = (*env)->NewWeakGlobalRef(env, io);
+        if (sb->ioRef == NULL) {
             JNU_ThrowByName(env,
                             "java/lang/OutOfMemoryError",
-                            "Setting Stream");
+                            "Setting I/O provider");
             return;
         }
     }
@@ -895,6 +904,7 @@
     streamBufferPtr sb = &data->streamBuf;
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
     int ret;
+    jobject input = NULL;
 
     /* This is where input suspends */
     if (sb->suspendable) {
@@ -920,9 +930,11 @@
      * Now fill a complete buffer, or as much of one as the stream
      * will give us if we are near the end.
      */
+    GET_IO_REF(input);
+
     RELEASE_ARRAYS(env, data, src->next_input_byte);
     ret = (*env)->CallIntMethod(env,
-                                sb->stream,
+                                input,
                                 JPEGImageReader_readInputDataID,
                                 sb->hstreamBuffer, 0,
                                 sb->bufferLength);
@@ -982,6 +994,7 @@
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
     jint ret;
     size_t offset, buflen;
+    jobject input = NULL;
 
     /*
      * The original (jpegdecoder.c) had code here that called
@@ -1003,6 +1016,9 @@
     if (src->next_input_byte > sb->buf) {
         memcpy(sb->buf, src->next_input_byte, offset);
     }
+
+    GET_IO_REF(input);
+
     RELEASE_ARRAYS(env, data, src->next_input_byte);
     buflen = sb->bufferLength - offset;
     if (buflen <= 0) {
@@ -1012,7 +1028,7 @@
         return;
     }
 
-    ret = (*env)->CallIntMethod(env, sb->stream,
+    ret = (*env)->CallIntMethod(env, input,
                                 JPEGImageReader_readInputDataID,
                                 sb->hstreamBuffer,
                                 offset, buflen);
@@ -1075,6 +1091,7 @@
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
     jlong ret;
     jobject reader;
+    jobject input = NULL;
 
     if (num_bytes < 0) {
         return;
@@ -1104,9 +1121,11 @@
         return;
     }
 
+    GET_IO_REF(input);
+
     RELEASE_ARRAYS(env, data, src->next_input_byte);
     ret = (*env)->CallLongMethod(env,
-                                 sb->stream,
+                                 input,
                                  JPEGImageReader_skipInputBytesID,
                                  (jlong) num_bytes);
     if ((*env)->ExceptionOccurred(env)
@@ -2285,11 +2304,14 @@
     imageIODataPtr data = (imageIODataPtr) cinfo->client_data;
     streamBufferPtr sb = &data->streamBuf;
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+    jobject output = NULL;
+
+    GET_IO_REF(output);
 
     RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
 
     (*env)->CallVoidMethod(env,
-                           sb->stream,
+                           output,
                            JPEGImageWriter_writeOutputDataID,
                            sb->hstreamBuffer,
                            0,
@@ -2322,11 +2344,16 @@
     /* find out how much needs to be written */
     /* this conversion from size_t to jint is safe, because the lenght of the buffer is limited by jint */
     jint datacount = (jint)(sb->bufferLength - dest->free_in_buffer);
+
     if (datacount != 0) {
+        jobject output = NULL;
+
+        GET_IO_REF(output);
+
         RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
 
         (*env)->CallVoidMethod(env,
-                               sb->stream,
+                               output,
                                JPEGImageWriter_writeOutputDataID,
                                sb->hstreamBuffer,
                                0,
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Tue Aug 06 17:01:05 2013 -0700
@@ -2606,38 +2606,37 @@
 
 #define ERR_BAD_IMAGE_LAYOUT (-2)
 
-#define CHECK_DST_ARRAY(start_offset, elements_per_pixel)             \
-    do {                                                              \
-        int offset = (start_offset);                                  \
-        int lastScanOffset;                                           \
-                                                                      \
-        if (!SAFE_TO_MULT(rasterP->scanlineStride,                    \
-                          (rasterP->height - 1)))                     \
-        {                                                             \
-            return ERR_BAD_IMAGE_LAYOUT;                              \
-        }                                                             \
-        lastScanOffset = rasterP->scanlineStride *                    \
-            (rasterP->height - 1);                                    \
-                                                                      \
-        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                   \
-            return ERR_BAD_IMAGE_LAYOUT;                              \
-        }                                                             \
-        lastScanOffset += offset;                                     \
-                                                                      \
-        if (!SAFE_TO_MULT((elements_per_pixel), rasterP->width)) {    \
-            return ERR_BAD_IMAGE_LAYOUT;                              \
-        }                                                             \
-        offset = (elements_per_pixel) * rasterP->width;               \
-                                                                      \
-        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                   \
-            return ERR_BAD_IMAGE_LAYOUT;                              \
-        }                                                             \
-        lastScanOffset += offset;                                     \
-                                                                      \
-        if (dataArrayLength < lastScanOffset) {                       \
-            return ERR_BAD_IMAGE_LAYOUT;                              \
-        }                                                             \
-    } while(0);                                                       \
+#define CHECK_DST_ARRAY(start_offset, elements_per_scan, elements_per_pixel) \
+    do {                                                                     \
+        int offset = (start_offset);                                         \
+        int lastScanOffset;                                                  \
+                                                                             \
+        if (!SAFE_TO_MULT((elements_per_scan),                               \
+                          (rasterP->height - 1)))                            \
+        {                                                                    \
+            return ERR_BAD_IMAGE_LAYOUT;                                     \
+        }                                                                    \
+        lastScanOffset = (elements_per_scan) * (rasterP->height - 1);        \
+                                                                             \
+        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                          \
+            return ERR_BAD_IMAGE_LAYOUT;                                     \
+        }                                                                    \
+        lastScanOffset += offset;                                            \
+                                                                             \
+        if (!SAFE_TO_MULT((elements_per_pixel), rasterP->width)) {           \
+            return ERR_BAD_IMAGE_LAYOUT;                                     \
+        }                                                                    \
+        offset = (elements_per_pixel) * rasterP->width;                      \
+                                                                             \
+        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                          \
+            return ERR_BAD_IMAGE_LAYOUT;                                     \
+        }                                                                    \
+        lastScanOffset += offset;                                            \
+                                                                             \
+        if (dataArrayLength < lastScanOffset) {                              \
+            return ERR_BAD_IMAGE_LAYOUT;                                     \
+        }                                                                    \
+    } while(0);                                                              \
 
 static int
 storeImageArray(JNIEnv *env, BufImageS_t *srcP, BufImageS_t *dstP,
@@ -2665,39 +2664,33 @@
 
     if (hintP->packing == BYTE_INTERLEAVED) {
         /* Write it back to the destination */
-        CHECK_DST_ARRAY(hintP->channelOffset, hintP->numChans);
+        if (rasterP->dataType != BYTE_DATA_TYPE) {
+            /* We are working with a raster which was marked
+               as a byte interleaved due to performance reasons.
+               So, we have to convert the length of the data
+               array to bytes as well.
+            */
+            if (!SAFE_TO_MULT(rasterP->dataSize, dataArrayLength)) {
+                return ERR_BAD_IMAGE_LAYOUT;
+            }
+            dataArrayLength *= rasterP->dataSize;
+        }
+
+        CHECK_DST_ARRAY(hintP->dataOffset, hintP->sStride, hintP->numChans);
         cmDataP = (unsigned char *) mlib_ImageGetData(mlibImP);
         mStride = mlib_ImageGetStride(mlibImP);
         dataP = (unsigned char *)(*env)->GetPrimitiveArrayCritical(env,
                                                       rasterP->jdata, NULL);
         if (dataP == NULL) return 0;
-        cDataP = dataP + hintP->channelOffset;
+        cDataP = dataP + hintP->dataOffset;
         for (y=0; y < rasterP->height;
-             y++, cmDataP += mStride, cDataP += rasterP->scanlineStride)
+             y++, cmDataP += mStride, cDataP += hintP->sStride)
         {
             memcpy(cDataP, cmDataP, rasterP->width*hintP->numChans);
         }
         (*env)->ReleasePrimitiveArrayCritical(env, rasterP->jdata, dataP,
                                               JNI_ABORT);
     }
-    else if (hintP->packing == SHORT_INTERLEAVED) {
-        /* Write it back to the destination */
-        unsigned short *sdataP, *sDataP;
-        unsigned short *smDataP = (unsigned short *)mlib_ImageGetData(mlibImP);
-        CHECK_DST_ARRAY(hintP->channelOffset, hintP->numChans);
-        mStride = mlib_ImageGetStride(mlibImP);
-        sdataP = (unsigned short *)(*env)->GetPrimitiveArrayCritical(env,
-                                                      rasterP->jdata, NULL);
-        if (sdataP == NULL) return -1;
-        sDataP = sdataP + hintP->channelOffset;
-        for (y=0; y < rasterP->height;
-            y++, smDataP += mStride, sDataP += rasterP->scanlineStride)
-        {
-            memcpy(sDataP, smDataP, rasterP->width*hintP->numChans);
-        }
-        (*env)->ReleasePrimitiveArrayCritical(env, rasterP->jdata, sdataP,
-                                              JNI_ABORT);
-    }
     else if (dstP->cmodel.cmType == DIRECT_CM_TYPE) {
         /* Just need to move bits */
         if (mlibImP->type == MLIB_BYTE) {
@@ -3499,7 +3492,7 @@
     }
 
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
@@ -3575,7 +3568,7 @@
     }
 
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
@@ -3651,7 +3644,7 @@
     }
 
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
@@ -3730,7 +3723,7 @@
     }
 
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
@@ -3827,7 +3820,7 @@
         return -1;
     }
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
@@ -3925,7 +3918,7 @@
     }
 
     dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
-    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], rasterP->scanlineStride, 1);
 
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
--- a/jdk/src/share/native/sun/font/layout/CanonShaping.cpp	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/share/native/sun/font/layout/CanonShaping.cpp	Tue Aug 06 17:01:05 2013 -0700
@@ -66,6 +66,16 @@
     le_int32 *indices = LE_NEW_ARRAY(le_int32, charCount);
     le_int32 i;
 
+    if (combiningClasses == NULL || indices == NULL) {
+        if (combiningClasses != NULL) {
+            LE_DELETE_ARRAY(combiningClasses);
+        }
+        if (indices != NULL) {
+            LE_DELETE_ARRAY(indices);
+        }
+        return;
+    }
+
     for (i = 0; i < charCount; i += 1) {
       combiningClasses[i] = classTable->getGlyphClass(classTable, (LEGlyphID) inChars[i], success);
         indices[i] = i;
--- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1099,6 +1099,15 @@
 
         if (category == PrinterName.class) {
             return (T)(new PrinterName(printer, null));
+        } else if (category == PrinterInfo.class) {
+            PrinterInfo pInfo = new PrinterInfo(printer, null);
+            AttributeClass ac = (getAttMap != null) ?
+                (AttributeClass)getAttMap.get(pInfo.getName())
+                : null;
+            if (ac != null) {
+                return (T)(new PrinterInfo(ac.getStringValue(), null));
+            }
+            return (T)pInfo;
         } else if (category == QueuedJobCount.class) {
             QueuedJobCount qjc = new QueuedJobCount(0);
             AttributeClass ac = (getAttMap != null) ?
@@ -1566,7 +1575,24 @@
         }
     }
 
+    String getDest() {
+        return printer;
+    }
+
     public String getName() {
+        /*
+         * Mac is using printer-info IPP attribute for its human-readable printer
+         * name and is also the identifier used in NSPrintInfo:setPrinter.
+         */
+        if (UnixPrintServiceLookup.isMac()) {
+            PrintServiceAttributeSet psaSet = this.getAttributes();
+            if (psaSet != null) {
+                PrinterInfo pName = (PrinterInfo)psaSet.get(PrinterInfo.class);
+                if (pName != null) {
+                    return pName.toString();
+                }
+            }
+        }
         return printer;
     }
 
--- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Tue Aug 06 17:01:05 2013 -0700
@@ -65,6 +65,7 @@
 import javax.print.attribute.PrintJobAttributeSet;
 import javax.print.attribute.PrintRequestAttribute;
 import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.PrintServiceAttributeSet;
 import javax.print.attribute.standard.Copies;
 import javax.print.attribute.standard.Destination;
 import javax.print.attribute.standard.DocumentName;
@@ -76,6 +77,7 @@
 import javax.print.attribute.standard.MediaSize;
 import javax.print.attribute.standard.MediaSizeName;
 import javax.print.attribute.standard.OrientationRequested;
+import javax.print.attribute.standard.PrinterName;
 import javax.print.attribute.standard.RequestingUserName;
 import javax.print.attribute.standard.NumberUp;
 import javax.print.attribute.standard.Sides;
@@ -120,6 +122,9 @@
     UnixPrintJob(PrintService service) {
         this.service = service;
         mDestination = service.getName();
+        if (UnixPrintServiceLookup.isMac()) {
+            mDestination = ((IPPPrintService)service).getDest();
+        }
         mDestType = UnixPrintJob.DESTPRINTER;
     }
 
--- a/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Tue Aug 06 17:01:05 2013 -0700
@@ -926,6 +926,11 @@
     *shmExt = canUseShmExt = CANT_USE_MITSHM;
     *shmPixmaps = canUseShmExtPixmaps = CANT_USE_MITSHM;
 
+    if (awt_display == (Display *)NULL) {
+        AWT_NOFLUSH_UNLOCK();
+        return;
+    }
+
     /**
      * XShmQueryExtension returns False in remote server case.
      * Unfortunately it also returns True in ssh case, so
--- a/jdk/src/solaris/native/sun/java2d/x11/XRBackendNative.c	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/solaris/native/sun/java2d/x11/XRBackendNative.c	Tue Aug 06 17:01:05 2013 -0700
@@ -112,6 +112,25 @@
 #define PKGINFO_LINE_LEN_MAX 256
 #define PKGINFO_LINE_CNT_MAX 50
 
+/*
+ * X protocol uses (u_int16)length to specify the length in 4 bytes quantities
+ * of the whole request.  Both XRenderFillRectangles() and XFillRectangles()
+ * have provisions to fragment into several requests if the number of rectangles
+ * plus the current x request does not fit into 65535*4 bytes.  While
+ * XRenderCreateLinearGradient() and XRenderCreateRadialGradient() have
+ * provisions to gracefully degrade if the resulting request would exceed
+ * 65535*4 bytes.
+ *
+ * Below, we define a cap of 65535*4 bytes for the maximum X request payload
+ * allowed for Non-(XRenderFillRectangles() or XFillRectangles()) API calls,
+ * just to be conservative.  This is offset by the size of our maximum x*Req
+ * type in this compilation unit, which is xRenderCreateRadiaGradientReq.
+ *
+ * Note that sizeof(xRenderCreateRadiaGradientReq) = 36
+ */
+#define MAX_PAYLOAD (262140u - 36u)
+#define MAXUINT (0xffffffffu)
+
 static jboolean IsXRenderAvailable(jboolean verbose) {
 
     void *xrenderlib;
@@ -267,13 +286,19 @@
     char *maskData;
     XImage* defaultImg;
     jfieldID maskImgID;
-    jlong fmt8 =
-        ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardA8));
-    jlong fmt32 =
-       ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardARGB32));
+    jlong fmt8;
+    jlong fmt32;
+
     jfieldID a8ID = (*env)->GetStaticFieldID(env, cls, "FMTPTR_A8", "J");
     jfieldID argb32ID = (*env)->GetStaticFieldID(env, cls, "FMTPTR_ARGB32", "J");
 
+    if (awt_display == (Display *)NULL) {
+        return;
+    }
+
+    fmt8 = ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardA8));
+    fmt32 = ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardARGB32));
+
     (*env)->SetStaticLongField(env, cls, a8ID, fmt8);
     (*env)->SetStaticLongField(env, cls, argb32ID, fmt32);
 
@@ -404,6 +429,10 @@
     if (rectCnt <= 256) {
         xRects = &sRects[0];
     } else {
+        if (MAXUINT / sizeof(XRectangle) < (unsigned)rectCnt) {
+            /* rectCnt too big, integer overflow */
+            return;
+        }
         xRects = (XRectangle *) malloc(sizeof(XRectangle) * rectCnt);
         if (xRects == NULL) {
             return;
@@ -460,6 +489,12 @@
    XFixed *stops;
    XLinearGradient grad;
 
+   if (MAX_PAYLOAD / (sizeof(XRenderColor) + sizeof(XFixed))
+       < (unsigned)numStops) {
+       /* numStops too big, payload overflow */
+       return -1;
+   }
+
    if ((pixels = (jshort *)
         (*env)->GetPrimitiveArrayCritical(env, pixelsArray, NULL)) == NULL) {
        return -1;
@@ -480,6 +515,18 @@
     colors = (XRenderColor *) malloc(numStops * sizeof(XRenderColor));
     stops =  (XFixed *) malloc(numStops * sizeof(XFixed));
 
+    if (colors == NULL || stops == NULL) {
+        if (colors != NULL) {
+            free(colors);
+        }
+        if (stops != NULL) {
+            free(stops);
+        }
+        (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
+        (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);
+        return -1;
+    }
+
     for (i=0; i < numStops; i++) {
       stops[i] = XDoubleToFixed(fractions[i]);
       colors[i].alpha = pixels[i*4 + 0];
@@ -527,6 +574,11 @@
    XFixed *stops;
    XRadialGradient grad;
 
+   if (MAX_PAYLOAD / (sizeof(XRenderColor) + sizeof(XFixed))
+       < (unsigned)numStops) {
+       /* numStops too big, payload overflow */
+       return -1;
+   }
 
    if ((pixels =
        (jshort *)(*env)->GetPrimitiveArrayCritical(env, pixelsArray, NULL)) == NULL) {
@@ -550,6 +602,18 @@
     colors = (XRenderColor *) malloc(numStops * sizeof(XRenderColor));
     stops =  (XFixed *) malloc(numStops * sizeof(XFixed));
 
+    if (colors == NULL || stops == NULL) {
+        if (colors != NULL) {
+            free(colors);
+        }
+        if (stops != NULL) {
+            free(stops);
+        }
+        (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
+        (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);
+        return -1;
+    }
+
     for (i=0; i < numStops; i++) {
       stops[i] = XDoubleToFixed(fractions[i]);
       colors[i].alpha = pixels[i*4 + 0];
@@ -708,6 +772,12 @@
     unsigned char *pixelData;
     int i;
 
+    if (MAX_PAYLOAD / (sizeof(XGlyphInfo) + sizeof(Glyph))
+        < (unsigned)glyphCnt) {
+        /* glyphCnt too big, payload overflow */
+        return;
+    }
+
     XGlyphInfo *xginfo = (XGlyphInfo *) malloc(sizeof(XGlyphInfo) * glyphCnt);
     Glyph *gid = (Glyph *) malloc(sizeof(Glyph) * glyphCnt);
 
@@ -770,6 +840,11 @@
 Java_sun_java2d_xr_XRBackendNative_XRFreeGlyphsNative
  (JNIEnv *env, jclass cls, jint glyphSet, jintArray gidArray, jint glyphCnt) {
 
+    if (MAX_PAYLOAD / sizeof(Glyph) < (unsigned)glyphCnt) {
+        /* glyphCnt too big, payload overflow */
+        return;
+    }
+
     /* The glyph ids are 32 bit but may be stored in a 64 bit long on
      * a 64 bit architecture. So optimise the 32 bit case to avoid
      * extra stack or heap allocations by directly referencing the
@@ -840,6 +915,15 @@
     unsigned int sids[256];
     int charCnt = 0;
 
+    if ((MAX_PAYLOAD / sizeof(XGlyphElt32) < (unsigned)eltCnt)
+        || (MAX_PAYLOAD / sizeof(unsigned int) < (unsigned)glyphCnt)
+        || ((MAX_PAYLOAD - sizeof(XGlyphElt32)*(unsigned)eltCnt) /
+            sizeof(unsigned int) < (unsigned)glyphCnt))
+    {
+        /* (eltCnt, glyphCnt) too big, payload overflow */
+        return;
+    }
+
     if (eltCnt <= 24) {
       xelts = &selts[0];
     }else {
@@ -938,6 +1022,11 @@
     if (rectCnt <= 256) {
       xRects = &sRects[0];
     } else {
+      if (MAXUINT / sizeof(XRectangle) < (unsigned)rectCnt) {
+        /* rectCnt too big, integer overflow */
+        return;
+      }
+
       xRects = (XRectangle *) malloc(sizeof(XRectangle) * rectCnt);
       if (xRects == NULL) {
         return;
--- a/jdk/src/windows/classes/sun/print/Win32PrintService.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/src/windows/classes/sun/print/Win32PrintService.java	Tue Aug 06 17:01:05 2013 -0700
@@ -445,7 +445,7 @@
 
         initMedia();
 
-        if ((mediaSizeNames == null) && (mediaSizeNames.length == 0)) {
+        if ((mediaSizeNames == null) || (mediaSizeNames.length == 0)) {
             return null;
         }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Graphics2D/DrawString/DrawRotatedString.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2013, 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.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+
+import javax.imageio.ImageIO;
+
+/**
+ * @test
+ * @bug 7190349
+ * @summary Verifies that we get correct direction, when draw rotated string.
+ * @author Sergey Bylokhov
+ * @run main/othervm DrawRotatedString
+ */
+public final class DrawRotatedString {
+
+    private static final int SIZE = 500;
+
+    public static void main(final String[] args) throws IOException {
+        BufferedImage bi = createBufferedImage(true);
+        verify(bi);
+        bi = createBufferedImage(false);
+        verify(bi);
+        System.out.println("Passed");
+    }
+
+    private static void verify(BufferedImage bi) throws IOException {
+        for (int i = 0; i < SIZE; ++i) {
+            for (int j = 0; j < 99; ++j) {
+                //Text should not appear before 100
+                if (bi.getRGB(i, j) != Color.RED.getRGB()) {
+                    ImageIO.write(bi, "png", new File("image.png"));
+                    throw new RuntimeException("Failed: wrong text location");
+                }
+            }
+        }
+    }
+
+    private static BufferedImage createBufferedImage(final boolean  aa) {
+        final BufferedImage bi = new BufferedImage(SIZE, SIZE,
+                                                   BufferedImage.TYPE_INT_RGB);
+        final Graphics2D bg = bi.createGraphics();
+        bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                            aa ? RenderingHints.VALUE_ANTIALIAS_ON
+                               : RenderingHints.VALUE_ANTIALIAS_OFF);
+        bg.setColor(Color.RED);
+        bg.fillRect(0, 0, SIZE, SIZE);
+        bg.translate(100, 100);
+        bg.rotate(Math.toRadians(90));
+        bg.setColor(Color.BLACK);
+        bg.setFont(bg.getFont().deriveFont(20.0f));
+        bg.drawString("MMMMMMMMMMMMMMMM", 0, 0);
+        bg.dispose();
+        return bi;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Graphics2D/IncorrectTextSize/IncorrectTextSize.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2013, 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.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+
+import javax.imageio.ImageIO;
+
+/**
+ * @test
+ * @bug 8013569
+ * @author Sergey Bylokhov
+ */
+public final class IncorrectTextSize {
+
+    static final int scale = 2;
+    static final int width = 1200;
+    static final int height = 100;
+    static BufferedImage bi = new BufferedImage(width, height,
+                                                BufferedImage.TYPE_INT_ARGB);
+    static final String TEXT = "The quick brown fox jumps over the lazy dog"
+            + "The quick brown fox jumps over the lazy dog";
+
+    public static void main(final String[] args) throws IOException {
+        for (int  point = 5; point < 11; ++point) {
+            Graphics2D g2d = bi.createGraphics();
+            g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point));
+            g2d.scale(scale, scale);
+            g2d.setColor(Color.WHITE);
+            g2d.fillRect(0, 0, width, height);
+            g2d.setColor(Color.green);
+            g2d.drawString(TEXT, 0, 20);
+            int length = g2d.getFontMetrics().stringWidth(TEXT);
+            if (length < 0) {
+                throw new RuntimeException("Negative length");
+            }
+            for (int i = (length + 1) * scale; i < width; ++i) {
+                for (int j = 0; j < height; ++j) {
+                    if (bi.getRGB(i, j) != Color.white.getRGB()) {
+                        g2d.drawLine(length, 0, length, height);
+                        ImageIO.write(bi, "png", new File("image.png"));
+                        System.out.println("length = " + length);
+                        System.err.println("Wrong color at x=" + i + ",y=" + j);
+                        System.err.println("Color is:" + new Color(bi.getRGB(i,
+                                                                             j)));
+                        throw new RuntimeException("Test failed.");
+                    }
+                }
+            }
+            g2d.dispose();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/plugins/jpeg/JpegWriterLeakTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2013, 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     8020983
+ * @summary Test verifies that jpeg writer instances are collected
+ *          even if destroy() or reset() methods is not invoked.
+ *
+ * @run main JpegWriterLeakTest
+ */
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Random;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.ImageOutputStream;
+
+public class JpegWriterLeakTest {
+
+    public static void main(String[] args) {
+        final ReferenceQueue<ImageWriter> queue = new ReferenceQueue<>();
+        final ArrayList<Reference<? extends ImageWriter>> refs = new ArrayList<>();
+
+        int count = 2;
+
+        do {
+            ImageWriter writer =
+                    ImageIO.getImageWritersByFormatName("jpeg").next();
+
+            final WeakReference<? extends ImageWriter> ref =
+                    new WeakReference<>(writer, queue);
+
+            refs.add(ref);
+
+
+            try {
+                final ImageOutputStream os =
+                        ImageIO.createImageOutputStream(new ByteArrayOutputStream());
+                writer.setOutput(os);
+
+                writer.write(getImage());
+
+
+                // NB: dispose() or reset() workarounds the problem.
+            } catch (IOException e) {
+            } finally {
+                writer = null;
+            }
+            count--;
+        } while (count > 0);
+
+
+        System.out.println("Wait for GC...");
+
+        final long testTimeOut = 60000L;
+
+        final long startTime = System.currentTimeMillis();
+
+        while (!refs.isEmpty()) {
+            // check for the test timeout
+            final long now = System.currentTimeMillis();
+
+            if (now - startTime > testTimeOut) {
+                System.out.println();
+                throw new RuntimeException("Test FAILED.");
+            }
+
+            System.gc();
+
+            try {
+                System.out.print(".");
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+            };
+
+            Reference<? extends ImageWriter> r = queue.poll();
+            if (r != null) {
+                System.out.println("Got reference: " + r);
+                refs.remove(r);
+            }
+        }
+        System.out.println("Test PASSED.");
+    }
+
+    private static BufferedImage getImage() {
+        int width = 2500;
+        int height = new Random().nextInt(2500) + 1;
+        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+
+        Graphics2D g = image.createGraphics();
+        g.setColor(Color.blue);
+        g.fillRect(0, 0, width, height);
+
+        return image;
+    }
+}
--- a/jdk/test/javax/print/DialogMargins.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/jdk/test/javax/print/DialogMargins.java	Tue Aug 06 17:01:05 2013 -0700
@@ -25,11 +25,12 @@
 
 /**
  * @test
- * @bug 4485755 6361370 6448717 5080051 6939417
+ * @bug 4485755 6361370 6448717 5080051 6939417 8016343
  * @summary dialog doesn't have way to specify margins
  *          for 6361370, verify exception for offline printer in Windows
  *          for 6448717, faster display of print dialog
  *          for 6500903, verify status of printer if accepting jobs or not
+ *          for 8016343, verify printing to non-default printer
  * @author prr
  * @run main/manual DialogMargins
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JComboBox/8015300/Test8015300.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2013, 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 com.sun.java.swing.plaf.windows.WindowsComboBoxUI.WindowsComboBoxEditor;
+import java.awt.Toolkit;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import javax.swing.ComboBoxEditor;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JTextField;
+import javax.swing.UIManager;
+import sun.awt.SunToolkit;
+
+import static javax.swing.SwingUtilities.invokeAndWait;
+import static javax.swing.SwingUtilities.windowForComponent;
+import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
+
+/*
+ * @test
+ * @bug 8015300
+ * @summary Tests that editable combobox select all text
+ * @author Sergey Malenkov
+ */
+
+public class Test8015300 {
+    private static final SunToolkit STK = (SunToolkit) Toolkit.getDefaultToolkit();
+    private static final String[] ITEMS = {
+            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
+            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
+
+    private static JComboBox<String> combo;
+
+    public static void main(String[] args) throws Exception {
+        UIManager.LookAndFeelInfo[] array = UIManager.getInstalledLookAndFeels();
+        for (UIManager.LookAndFeelInfo info : array) {
+            UIManager.setLookAndFeel(info.getClassName());
+            System.err.println("L&F: " + info.getName());
+            invokeAndWait(new Runnable() {
+                @Override
+                public void run() {
+                    combo = new JComboBox<>(ITEMS);
+                    combo.addItemListener(new ItemListener() {
+                        @Override
+                        public void itemStateChanged(ItemEvent event) {
+                            if (ItemEvent.SELECTED == event.getStateChange() && combo.isEditable()) {
+                                ComboBoxEditor editor = combo.getEditor();
+                                Object component = editor.getEditorComponent();
+                                if (component instanceof JTextField) {
+                                    JTextField text = (JTextField) component;
+                                    boolean selected = null != text.getSelectedText();
+
+                                    StringBuilder sb = new StringBuilder();
+                                    sb.append(" - ").append(combo.getSelectedIndex());
+                                    sb.append(": ").append(event.getItem());
+                                    if (selected) {
+                                        sb.append("; selected");
+                                    }
+                                    System.err.println(sb);
+                                    if ((editor instanceof WindowsComboBoxEditor) == (null == text.getSelectedText())) {
+                                        throw new Error("unexpected state of text selection");
+                                    }
+                                }
+                            }
+                        }
+                    });
+                    JFrame frame = new JFrame(getClass().getSimpleName());
+                    frame.add(combo);
+                    frame.pack();
+                    frame.setLocationRelativeTo(null);
+                    frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+                    frame.setVisible(true);
+                }
+            });
+            for (int i = 0; i < ITEMS.length; ++i) {
+                select(i, true);
+                select(1, false);
+            }
+            invokeAndWait(new Runnable() {
+                @Override
+                public void run() {
+                    windowForComponent(combo).dispose();
+                }
+            });
+        }
+    }
+
+    private static void select(final int index, final boolean editable) throws Exception {
+        invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                combo.setEditable(editable);
+                combo.setSelectedIndex(index);
+            }
+        });
+        STK.realSync();
+        Thread.sleep(50L);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/plaf/synth/Test8015926.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2013, 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 8015926
+ * @summary Tests that there are no NPE during painting
+ * @author Sergey Malenkov
+ */
+
+import javax.swing.JFrame;
+import javax.swing.JTree;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+
+import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
+
+public class Test8015926 implements TreeModelListener, Runnable, Thread.UncaughtExceptionHandler {
+
+    public static void main(String[] args) throws Exception {
+        UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
+        SwingUtilities.invokeAndWait(new Test8015926());
+        Thread.sleep(1000L);
+    }
+
+    private JTree tree;
+
+    @Override
+    public void treeStructureChanged(TreeModelEvent event) {
+    }
+
+    @Override
+    public void treeNodesRemoved(TreeModelEvent event) {
+    }
+
+    @Override
+    public void treeNodesInserted(TreeModelEvent event) {
+        this.tree.expandPath(event.getTreePath());
+    }
+
+    @Override
+    public void treeNodesChanged(TreeModelEvent event) {
+    }
+
+    @Override
+    public void run() {
+        Thread.currentThread().setUncaughtExceptionHandler(this);
+
+        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
+        DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child");
+        DefaultTreeModel model = new DefaultTreeModel(root);
+
+        this.tree = new JTree();
+        this.tree.setModel(model);
+
+        JFrame frame = new JFrame(getClass().getSimpleName());
+        frame.add(this.tree);
+
+        model.addTreeModelListener(this); // frame is not visible yet
+        model.insertNodeInto(child, root, root.getChildCount());
+        model.removeNodeFromParent(child);
+
+        frame.setSize(640, 480);
+        frame.setLocationRelativeTo(null);
+        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+        frame.setVisible(true);
+    }
+
+    @Override
+    public void uncaughtException(Thread thread, Throwable exception) {
+        exception.printStackTrace();
+        System.exit(1);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/awt/image/ImagingLib/SamePackingTypeTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2013, 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     8019201
+ * @summary Test verifies that medialib glue code does not throw
+ *          an ImagingOpException for certain pairs of source and
+ *          destination images.
+ *
+ * @run main SamePackingTypeTest
+ */
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import static java.awt.image.BufferedImage.TYPE_4BYTE_ABGR;
+import static java.awt.image.BufferedImage.TYPE_4BYTE_ABGR_PRE;
+import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
+import static java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE;
+import java.awt.image.BufferedImageOp;
+import java.awt.image.ConvolveOp;
+import java.awt.image.ImagingOpException;
+import java.awt.image.Kernel;
+import java.util.Arrays;
+
+
+public class SamePackingTypeTest {
+
+    public static void main(String[] args) {
+        BufferedImageOp op = createTestOp();
+
+        try {
+            System.out.print("Integer-based images... ");
+            doTest(op, TYPE_INT_ARGB, TYPE_INT_ARGB_PRE);
+            System.out.println("done.");
+
+            System.out.print("Byte-based images... ");
+            doTest(op, TYPE_4BYTE_ABGR, TYPE_4BYTE_ABGR_PRE);
+            System.out.println("done");
+        } catch (ImagingOpException e) {
+            throw new RuntimeException("Test FAILED", e);
+        }
+    }
+
+    private static void doTest(BufferedImageOp op, int stype, int dtype) {
+        final int size = 100;
+
+        final BufferedImage src = new BufferedImage(size, size, stype);
+        Graphics2D g = src.createGraphics();
+        g.setColor(Color.red);
+        g.fillRect(0, 0, size, size);
+        g.dispose();
+
+
+        final BufferedImage dst = new BufferedImage(size, size, dtype);
+        g = dst.createGraphics();
+        g.setColor(Color.blue);
+        g.fillRect(0, 0, size, size);
+        g.dispose();
+
+        op.filter(src, dst);
+
+        final int rgb = dst.getRGB(size - 1, size - 1);
+        System.out.printf("dst: 0x%X ", rgb);
+
+        if (rgb != 0xFFFF0000) {
+            throw new RuntimeException(String.format("Wrong color in dst: 0x%X", rgb));
+        }
+    }
+
+    private static BufferedImageOp createTestOp() {
+        final int size = 1;
+        final float v = 1f / (size * size);
+        final float[] k_data = new float[size * size];
+        Arrays.fill(k_data, v);
+
+        Kernel k = new Kernel(size, size, k_data);
+        return new ConvolveOp(k);
+    }
+}
--- a/langtools/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -222,3 +222,4 @@
 ce5a90df517bdceb2739d7dd3e6764b070def802 jdk8-b98
 6d85acab769eb79bc058f5640fa86a6ef096a583 jdk8-b99
 82f68da70e471ee5640016e3f38c014347a5c785 jdk8-b100
+0324dbf07b0f1cc51ad9fa18976489d02d23b60d jdk8-b101
--- a/langtools/src/share/classes/com/sun/source/util/DocTrees.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/source/util/DocTrees.java	Tue Aug 06 17:01:05 2013 -0700
@@ -30,7 +30,6 @@
 import javax.tools.JavaCompiler.CompilationTask;
 
 import com.sun.source.doctree.DocCommentTree;
-import com.sun.source.doctree.ReferenceTree;
 import javax.tools.Diagnostic;
 
 /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1621,6 +1621,7 @@
                     text = removeNonInlineHtmlTags(text);
                 }
                 text = Util.replaceTabs(configuration, text);
+                text = Util.normalizeNewlines(text);
                 result.addContent(new RawHtml(text));
             }
         }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java	Tue Aug 06 17:01:05 2013 -0700
@@ -71,7 +71,7 @@
      * {@inheritDoc}
      */
     protected Content codeTagOutput(Tag tag) {
-        Content result = HtmlTree.CODE(new StringContent(tag.text()));
+        Content result = HtmlTree.CODE(new StringContent(Util.normalizeNewlines(tag.text())));
         return result;
     }
 
@@ -135,7 +135,7 @@
      * {@inheritDoc}
      */
     protected Content literalTagOutput(Tag tag) {
-        Content result = new StringContent(tag.text());
+        Content result = new StringContent(Util.normalizeNewlines(tag.text()));
         return result;
     }
 
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java	Tue Aug 06 17:01:05 2013 -0700
@@ -631,6 +631,32 @@
         return result.toString();
     }
 
+    public static String normalizeNewlines(String text) {
+        StringBuilder sb = new StringBuilder();
+        final int textLength = text.length();
+        final String NL = DocletConstants.NL;
+        int pos = 0;
+        for (int i = 0; i < textLength; i++) {
+            char ch = text.charAt(i);
+            switch (ch) {
+                case '\n':
+                    sb.append(text, pos, i);
+                    sb.append(NL);
+                    pos = i + 1;
+                    break;
+                case '\r':
+                    sb.append(text, pos, i);
+                    sb.append(NL);
+                    if (i + 1 < textLength && text.charAt(i + 1) == '\n')
+                        i++;
+                    pos = i + 1;
+                    break;
+            }
+        }
+        sb.append(text, pos, textLength);
+        return sb.toString();
+    }
+
     /**
      * The documentation for values() and valueOf() in Enums are set by the
      * doclet.
--- a/langtools/src/share/classes/com/sun/tools/doclint/Checker.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Checker.java	Tue Aug 06 17:01:05 2013 -0700
@@ -31,9 +31,11 @@
 import java.net.URISyntaxException;
 import java.util.Deque;
 import java.util.EnumSet;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -45,6 +47,7 @@
 import javax.lang.model.type.TypeKind;
 import javax.lang.model.type.TypeMirror;
 import javax.tools.Diagnostic.Kind;
+import javax.tools.JavaFileObject;
 
 import com.sun.source.doctree.AttributeTree;
 import com.sun.source.doctree.AuthorTree;
@@ -88,9 +91,9 @@
 public class Checker extends DocTreePathScanner<Void, Void> {
     final Env env;
 
-    Set<Element> foundParams = new HashSet<Element>();
-    Set<TypeMirror> foundThrows = new HashSet<TypeMirror>();
-    Set<String> foundAnchors = new HashSet<String>();
+    Set<Element> foundParams = new HashSet<>();
+    Set<TypeMirror> foundThrows = new HashSet<>();
+    Map<JavaFileObject, Set<String>> foundAnchors = new HashMap<>();
     boolean foundInheritDoc = false;
     boolean foundReturn = false;
 
@@ -129,7 +132,7 @@
     Checker(Env env) {
         env.getClass();
         this.env = env;
-        tagStack = new LinkedList<TagStackItem>();
+        tagStack = new LinkedList<>();
         implicitHeaderLevel = env.implicitHeaderLevel;
     }
 
@@ -138,10 +141,27 @@
 
         boolean isOverridingMethod = !env.currOverriddenMethods.isEmpty();
 
-        if (tree == null) {
-            if (!isSynthetic() && !isOverridingMethod)
-                reportMissing("dc.missing.comment");
-            return null;
+        if (p.getLeaf() == p.getCompilationUnit()) {
+            // If p points to a compilation unit, the implied declaration is the
+            // package declaration (if any) for the compilation unit.
+            // Handle this case specially, because doc comments are only
+            // expected in package-info files.
+            JavaFileObject fo = p.getCompilationUnit().getSourceFile();
+            boolean isPkgInfo = fo.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
+            if (tree == null) {
+                if (isPkgInfo)
+                    reportMissing("dc.missing.comment");
+                return null;
+            } else {
+                if (!isPkgInfo)
+                    reportReference("dc.unexpected.comment");
+            }
+        } else {
+            if (tree == null) {
+                if (!isSynthetic() && !isOverridingMethod)
+                    reportMissing("dc.missing.comment");
+                return null;
+            }
         }
 
         tagStack.clear();
@@ -184,6 +204,10 @@
         env.messages.report(MISSING, Kind.WARNING, env.currPath.getLeaf(), code, args);
     }
 
+    private void reportReference(String code, Object... args) {
+        env.messages.report(REFERENCE, Kind.WARNING, env.currPath.getLeaf(), code, args);
+    }
+
     @Override
     public Void visitDocComment(DocCommentTree tree, Void ignore) {
         super.visitDocComment(tree, ignore);
@@ -508,7 +532,7 @@
                             if (!validName.matcher(value).matches()) {
                                 env.messages.error(HTML, tree, "dc.invalid.anchor", value);
                             }
-                            if (!foundAnchors.add(value)) {
+                            if (!checkAnchor(value)) {
                                 env.messages.error(HTML, tree, "dc.anchor.already.defined", value);
                             }
                         }
@@ -551,6 +575,14 @@
         return super.visitAttribute(tree, ignore);
     }
 
+    private boolean checkAnchor(String name) {
+        JavaFileObject fo = env.currPath.getCompilationUnit().getSourceFile();
+        Set<String> set = foundAnchors.get(fo);
+        if (set == null)
+            foundAnchors.put(fo, set = new HashSet<>());
+        return set.add(name);
+    }
+
     // http://www.w3.org/TR/html401/types.html#type-name
     private static final Pattern validName = Pattern.compile("[A-Za-z][A-Za-z0-9-_:.]*");
 
@@ -721,8 +753,7 @@
         Element ex = env.trees.getElement(new DocTreePath(getCurrentPath(), exName));
         if (ex == null) {
             env.messages.error(REFERENCE, tree, "dc.ref.not.found");
-        } else if (ex.asType().getKind() == TypeKind.DECLARED
-                && env.types.isAssignable(ex.asType(), env.java_lang_Throwable)) {
+        } else if (isThrowable(ex.asType())) {
             switch (env.currElement.getKind()) {
                 case CONSTRUCTOR:
                 case METHOD:
@@ -741,6 +772,15 @@
         return scan(tree.getDescription(), ignore);
     }
 
+    private boolean isThrowable(TypeMirror tm) {
+        switch (tm.getKind()) {
+            case DECLARED:
+            case TYPEVAR:
+                return env.types.isAssignable(tm, env.java_lang_Throwable);
+        }
+        return false;
+    }
+
     private void checkThrowsDeclared(ReferenceTree tree, TypeMirror t, List<? extends TypeMirror> list) {
         boolean found = false;
         for (TypeMirror tl : list) {
--- a/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java	Tue Aug 06 17:01:05 2013 -0700
@@ -30,7 +30,6 @@
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.regex.Pattern;
 
 import javax.lang.model.element.Name;
 import javax.tools.StandardLocation;
@@ -166,8 +165,8 @@
     }
 
     void processArgs(String... args) throws BadArgs {
-        javacOpts = new ArrayList<String>();
-        javacFiles = new ArrayList<File>();
+        javacOpts = new ArrayList<>();
+        javacFiles = new ArrayList<>();
 
         if (args.length == 0)
             needHelp = true;
@@ -214,7 +213,7 @@
     }
 
     List<File> splitPath(String path) {
-        List<File> files = new ArrayList<File>();
+        List<File> files = new ArrayList<>();
         for (String f: path.split(File.pathSeparator)) {
             if (f.length() > 0)
                 files.add(new File(f));
@@ -279,7 +278,6 @@
             TaskListener tl = new TaskListener() {
                 @Override
                 public void started(TaskEvent e) {
-                    return;
                 }
 
                 @Override
--- a/langtools/src/share/classes/com/sun/tools/doclint/resources/doclint.properties	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/doclint/resources/doclint.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -67,6 +67,7 @@
 dc.tag.start.unmatched = end tag missing: </{0}>
 dc.tag.unknown = unknown tag: {0}
 dc.text.not.allowed = text not allowed in <{0}> element
+dc.unexpected.comment=documentation comment not expected here
 
 dc.main.ioerror=IO error: {0}
 dc.main.no.files.given=No files given
--- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Tue Aug 06 17:01:05 2013 -0700
@@ -69,7 +69,6 @@
 import com.sun.tools.javac.code.Type.ErrorType;
 import com.sun.tools.javac.code.Type.UnionClassType;
 import com.sun.tools.javac.code.Types;
-import com.sun.tools.javac.code.TypeTag;
 import com.sun.tools.javac.code.Types.TypeRelation;
 import com.sun.tools.javac.comp.Attr;
 import com.sun.tools.javac.comp.AttrContext;
@@ -358,7 +357,7 @@
         Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
                 new Log.DeferredDiagnosticHandler(log);
         try {
-            final ClassSymbol tsym;
+            final TypeSymbol tsym;
             final Name memberName;
             if (ref.qualifierExpression == null) {
                 tsym = env.enclClass.sym;
@@ -387,7 +386,7 @@
                         return null;
                     }
                 } else {
-                    tsym = (ClassSymbol) t.tsym;
+                    tsym = t.tsym;
                     memberName = ref.memberName;
                 }
             }
@@ -408,15 +407,17 @@
                 paramTypes = lb.toList();
             }
 
-            Symbol msym = (memberName == tsym.name)
-                    ? findConstructor(tsym, paramTypes)
-                    : findMethod(tsym, memberName, paramTypes);
+            ClassSymbol sym = (ClassSymbol) types.upperBound(tsym.type).tsym;
+
+            Symbol msym = (memberName == sym.name)
+                    ? findConstructor(sym, paramTypes)
+                    : findMethod(sym, memberName, paramTypes);
             if (paramTypes != null) {
                 // explicit (possibly empty) arg list given, so cannot be a field
                 return msym;
             }
 
-            VarSymbol vsym = (ref.paramTypes != null) ? null : findField(tsym, memberName);
+            VarSymbol vsym = (ref.paramTypes != null) ? null : findField(sym, memberName);
             // prefer a field over a method with no parameters
             if (vsym != null &&
                     (msym == null ||
@@ -789,6 +790,7 @@
                 case METHOD:
 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
                     method = (JCMethodDecl)tree;
+                    env = memberEnter.getMethodEnv(method, env);
                     break;
                 case VARIABLE:
 //                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
@@ -800,7 +802,6 @@
                         try {
                             Assert.check(method.body == tree);
                             method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
-                            env = memberEnter.getMethodEnv(method, env);
                             env = attribStatToTree(method.body, env, copier.leafCopy);
                         } finally {
                             method.body = (JCBlock) tree;
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java	Tue Aug 06 17:01:05 2013 -0700
@@ -596,7 +596,7 @@
 
     // This method is part of the javax.lang.model API, do not use this in javac code.
     public <A extends java.lang.annotation.Annotation> A[] getAnnotationsByType(Class<A> annoType) {
-        return JavacAnnoConstructs.getAnnotations(this, annoType);
+        return JavacAnnoConstructs.getAnnotationsByType(this, annoType);
     }
 
     // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Tue Aug 06 17:01:05 2013 -0700
@@ -134,7 +134,7 @@
      * @return the upper bound of the given type
      */
     public Type upperBound(Type t) {
-        return upperBound.visit(t);
+        return upperBound.visit(t).unannotatedType();
     }
     // where
         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
@@ -620,7 +620,9 @@
      * (ii) perform functional interface bridge calculation.
      */
     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
-        Assert.check(targets.nonEmpty() && isFunctionalInterface(targets.head));
+        if (targets.isEmpty() || !isFunctionalInterface(targets.head)) {
+            return null;
+        }
         Symbol descSym = findDescriptorSymbol(targets.head.tsym);
         Type descType = findDescriptorType(targets.head);
         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
@@ -1130,9 +1132,9 @@
 
                     HashSet<UniqueType> set = new HashSet<UniqueType>();
                     for (Type x : interfaces(t))
-                        set.add(new UniqueType(x, Types.this));
+                        set.add(new UniqueType(x.unannotatedType(), Types.this));
                     for (Type x : interfaces(s)) {
-                        if (!set.remove(new UniqueType(x, Types.this)))
+                        if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
                             return false;
                     }
                     return (set.isEmpty());
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Annotate.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Annotate.java	Tue Aug 06 17:01:05 2013 -0700
@@ -273,7 +273,7 @@
                 continue;
             }
             JCIdent left = (JCIdent)assign.lhs;
-            Symbol method = rs.resolveQualifiedMethod(left.pos(),
+            Symbol method = rs.resolveQualifiedMethod(assign.rhs.pos(),
                                                           env,
                                                           a.type,
                                                           left.name,
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1948,6 +1948,8 @@
             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
                                                  ((JCIdent) clazzid).name);
 
+            EndPosTable endPosTable = this.env.toplevel.endPositions;
+            endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
             if (clazz.hasTag(ANNOTATED_TYPE)) {
                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
                 List<JCAnnotation> annos = annoType.annotations;
@@ -2193,7 +2195,9 @@
                         syms.objectType :
                         clazztype;
                 if (!inferred.isErroneous() &&
-                    types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings)) {
+                    (allowPoly && pt() == Infer.anyPoly ?
+                        types.isSameType(inferred, clazztype) :
+                        types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
                     String key = types.isSameType(clazztype, inferred) ?
                         "diamond.redundant.args" :
                         "diamond.redundant.args.1";
@@ -2968,7 +2972,9 @@
                 //check that functional interface class is well-formed
                 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
                         names.empty, List.of(fExpr.targets.head), ABSTRACT);
-                chk.checkImplementations(env.tree, csym, csym);
+                if (csym != null) {
+                    chk.checkImplementations(env.tree, csym, csym);
+                }
             }
         }
     }
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java	Tue Aug 06 17:01:05 2013 -0700
@@ -2997,7 +2997,8 @@
         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
                 e != null;
                 e = e.sibling)
-            if (e.sym.kind == MTH && e.sym.name != names.clinit)
+            if (e.sym.kind == MTH && e.sym.name != names.clinit &&
+                    (e.sym.flags() & SYNTHETIC) == 0)
                 members.add((MethodSymbol) e.sym);
 
         // remove the ones that are assigned values
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Env.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Env.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, 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
@@ -124,7 +124,16 @@
 
     @Override
     public String toString() {
-        return "Env[" + info + (outer == null ? "" : ",outer=" + outer) + "]";
+        StringBuilder sb = new StringBuilder();
+        sb.append("Env[").append(info);
+//        if (enclMethod != null)
+//            sb.append(",enclMethod=").append(Pretty.toSimpleString(enclMethod));
+//        if (enclClass != null)
+//            sb.append(",enclClass=").append(Pretty.toSimpleString(enclClass));
+        if (outer != null)
+            sb.append(",outer=").append(outer);
+        sb.append("]");
+        return sb.toString();
     }
 
     public Iterator<Env<A>> iterator() {
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1339,7 +1339,7 @@
 
         /** A mapping from addresses to variable symbols.
          */
-        VarSymbol[] vars;
+        JCVariableDecl[] vardecls;
 
         /** The current class being defined.
          */
@@ -1417,13 +1417,14 @@
          *  to the next available sequence number and entering it under that
          *  index into the vars array.
          */
-        void newVar(VarSymbol sym) {
-            vars = ArrayUtils.ensureCapacity(vars, nextadr);
+        void newVar(JCVariableDecl varDecl) {
+            VarSymbol sym = varDecl.sym;
+            vardecls = ArrayUtils.ensureCapacity(vardecls, nextadr);
             if ((sym.flags() & FINAL) == 0) {
                 sym.flags_field |= EFFECTIVELY_FINAL;
             }
             sym.adr = nextadr;
-            vars[nextadr] = sym;
+            vardecls[nextadr] = varDecl;
             inits.excl(nextadr);
             uninits.incl(nextadr);
             nextadr++;
@@ -1493,11 +1494,13 @@
         /** Check that trackable variable is initialized.
          */
         void checkInit(DiagnosticPosition pos, VarSymbol sym) {
+            checkInit(pos, sym, "var.might.not.have.been.initialized");
+        }
+        void checkInit(DiagnosticPosition pos, VarSymbol sym, String errkey) {
             if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
                 trackable(sym) &&
                 !inits.isMember(sym.adr)) {
-                log.error(pos, "var.might.not.have.been.initialized",
-                          sym);
+                log.error(pos, errkey, sym);
                 inits.incl(sym.adr);
             }
         }
@@ -1599,7 +1602,7 @@
                         if ((def.mods.flags & STATIC) != 0) {
                             VarSymbol sym = def.sym;
                             if (trackable(sym))
-                                newVar(sym);
+                                newVar(def);
                         }
                     }
                 }
@@ -1619,7 +1622,7 @@
                         if ((def.mods.flags & STATIC) == 0) {
                             VarSymbol sym = def.sym;
                             if (trackable(sym))
-                                newVar(sym);
+                                newVar(def);
                         }
                     }
                 }
@@ -1678,9 +1681,22 @@
                 scan(tree.body);
 
                 if (isInitialConstructor) {
-                    for (int i = firstadr; i < nextadr; i++)
-                        if (vars[i].owner == classDef.sym)
-                            checkInit(TreeInfo.diagEndPos(tree.body), vars[i]);
+                    boolean isSynthesized = (tree.sym.flags() &
+                                             GENERATEDCONSTR) != 0;
+                    for (int i = firstadr; i < nextadr; i++) {
+                        JCVariableDecl vardecl = vardecls[i];
+                        VarSymbol var = vardecl.sym;
+                        if (var.owner == classDef.sym) {
+                            // choose the diagnostic position based on whether
+                            // the ctor is default(synthesized) or not
+                            if (isSynthesized) {
+                                checkInit(TreeInfo.diagnosticPositionFor(var, vardecl),
+                                    var, "var.not.initialized.in.default.constructor");
+                            } else {
+                                checkInit(TreeInfo.diagEndPos(tree.body), var);
+                            }
+                        }
+                    }
                 }
                 List<AssignPendingExit> exits = pendingExits.toList();
                 pendingExits = new ListBuffer<AssignPendingExit>();
@@ -1691,7 +1707,7 @@
                     if (isInitialConstructor) {
                         inits.assign(exit.exit_inits);
                         for (int i = firstadr; i < nextadr; i++)
-                            checkInit(exit.tree.pos(), vars[i]);
+                            checkInit(exit.tree.pos(), vardecls[i].sym);
                     }
                 }
             } finally {
@@ -1706,7 +1722,7 @@
 
         public void visitVarDef(JCVariableDecl tree) {
             boolean track = trackable(tree.sym);
-            if (track && tree.sym.owner.kind == MTH) newVar(tree.sym);
+            if (track && tree.sym.owner.kind == MTH) newVar(tree);
             if (tree.init != null) {
                 Lint lintPrev = lint;
                 lint = lint.augment(tree.sym);
@@ -2239,11 +2255,11 @@
                 Flow.this.make = make;
                 startPos = tree.pos().getStartPosition();
 
-                if (vars == null)
-                    vars = new VarSymbol[32];
+                if (vardecls == null)
+                    vardecls = new JCVariableDecl[32];
                 else
-                    for (int i=0; i<vars.length; i++)
-                        vars[i] = null;
+                    for (int i=0; i<vardecls.length; i++)
+                        vardecls[i] = null;
                 firstadr = 0;
                 nextadr = 0;
                 pendingExits = new ListBuffer<AssignPendingExit>();
@@ -2255,8 +2271,8 @@
                 startPos = -1;
                 resetBits(inits, uninits, uninitsTry, initsWhenTrue,
                         initsWhenFalse, uninitsWhenTrue, uninitsWhenFalse);
-                if (vars != null) for (int i=0; i<vars.length; i++)
-                    vars[i] = null;
+                if (vardecls != null) for (int i=0; i<vardecls.length; i++)
+                    vardecls[i] = null;
                 firstadr = 0;
                 nextadr = 0;
                 pendingExits = null;
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1240,7 +1240,8 @@
         CAPTURED(InferenceBound.UPPER) {
             @Override
             public boolean accepts(UndetVar t, InferenceContext inferenceContext) {
-                return !inferenceContext.free(t.getBounds(InferenceBound.UPPER, InferenceBound.LOWER));
+                return t.isCaptured() &&
+                        !inferenceContext.free(t.getBounds(InferenceBound.UPPER, InferenceBound.LOWER));
             }
 
             @Override
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Aug 06 17:01:05 2013 -0700
@@ -2649,6 +2649,13 @@
                                   InferenceContext inferenceContext) {
         MethodResolutionPhase maxPhase = boxingAllowed ? VARARITY : BASIC;
 
+        if (site.hasTag(TYPEVAR)) {
+            return resolveMemberReference(pos, env, referenceTree, site.getUpperBound(),
+                    name, argtypes, typeargtypes, boxingAllowed, methodCheck, inferenceContext);
+        }
+
+        site = types.capture(site);
+
         ReferenceLookupHelper boundLookupHelper;
         if (!name.equals(names.init)) {
             //method reference
@@ -2675,24 +2682,52 @@
 
         //merge results
         Pair<Symbol, ReferenceLookupHelper> res;
-        if (!lookupSuccess(unboundSym)) {
-            res = new Pair<Symbol, ReferenceLookupHelper>(boundSym, boundLookupHelper);
-            env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
-        } else if (lookupSuccess(boundSym)) {
-            res = new Pair<Symbol, ReferenceLookupHelper>(ambiguityError(boundSym, unboundSym), boundLookupHelper);
-            env.info.pendingResolutionPhase = boundEnv.info.pendingResolutionPhase;
-        } else {
-            res = new Pair<Symbol, ReferenceLookupHelper>(unboundSym, unboundLookupHelper);
-            env.info.pendingResolutionPhase = unboundEnv.info.pendingResolutionPhase;
-        }
+        Symbol bestSym = choose(boundSym, unboundSym);
+        res = new Pair<Symbol, ReferenceLookupHelper>(bestSym,
+                bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper);
+        env.info.pendingResolutionPhase = bestSym == unboundSym ?
+                unboundEnv.info.pendingResolutionPhase :
+                boundEnv.info.pendingResolutionPhase;
 
         return res;
     }
-    //private
-        boolean lookupSuccess(Symbol s) {
+    //where
+        private Symbol choose(Symbol s1, Symbol s2) {
+            if (lookupSuccess(s1) && lookupSuccess(s2)) {
+                return ambiguityError(s1, s2);
+            } else if (lookupSuccess(s1) ||
+                    (canIgnore(s2) && !canIgnore(s1))) {
+                return s1;
+            } else if (lookupSuccess(s2) ||
+                    (canIgnore(s1) && !canIgnore(s2))) {
+                return s2;
+            } else {
+                return s1;
+            }
+        }
+
+        private boolean lookupSuccess(Symbol s) {
             return s.kind == MTH || s.kind == AMBIGUOUS;
         }
 
+        private boolean canIgnore(Symbol s) {
+            switch (s.kind) {
+                case ABSENT_MTH:
+                    return true;
+                case WRONG_MTH:
+                    InapplicableSymbolError errSym =
+                            (InapplicableSymbolError)s;
+                    return new Template(MethodCheckDiag.ARITY_MISMATCH.regex())
+                            .matches(errSym.errCandidate().snd);
+                case WRONG_MTHS:
+                    InapplicableSymbolsError errSyms =
+                            (InapplicableSymbolsError)s;
+                    return errSyms.filterCandidates(errSyms.mapCandidates()).isEmpty();
+                default:
+                    return false;
+            }
+        }
+
     /**
      * Helper for defining custom method-like lookup logic; a lookup helper
      * provides hooks for (i) the actual lookup logic and (ii) accessing the
@@ -3504,7 +3539,9 @@
                 List<Type> argtypes,
                 List<Type> typeargtypes) {
             Map<Symbol, JCDiagnostic> candidatesMap = mapCandidates();
-            Map<Symbol, JCDiagnostic> filteredCandidates = filterCandidates(candidatesMap);
+            Map<Symbol, JCDiagnostic> filteredCandidates = compactMethodDiags ?
+                    filterCandidates(candidatesMap) :
+                    mapCandidates();
             if (filteredCandidates.isEmpty()) {
                 filteredCandidates = candidatesMap;
             }
@@ -3556,8 +3593,7 @@
                 Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
                 for (Map.Entry<Symbol, JCDiagnostic> _entry : candidatesMap.entrySet()) {
                     JCDiagnostic d = _entry.getValue();
-                    if (!compactMethodDiags ||
-                            !new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
+                    if (!new Template(MethodCheckDiag.ARITY_MISMATCH.regex()).matches(d)) {
                         candidates.put(_entry.getKey(), d);
                     }
                 }
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/TransTypes.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/TransTypes.java	Tue Aug 06 17:01:05 2013 -0700
@@ -674,7 +674,11 @@
         if (tree.varargsElement != null)
             tree.varargsElement = types.erasure(tree.varargsElement);
         else
-            Assert.check(tree.args.length() == argtypes.length());
+            if (tree.args.length() != argtypes.length()) {
+                log.error(tree.pos(),
+                              "method.invoked.with.incorrect.number.arguments",
+                              tree.args.length(), argtypes.length());
+            }
         tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
 
         tree.type = types.erasure(tree.type);
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1820,7 +1820,6 @@
                 msym.externalType(types).getParameterTypes());
         if (!msym.isDynamic()) {
             code.statBegin(tree.pos);
-            code.markStatBegin();
         }
         result = m.invoke();
     }
--- a/langtools/src/share/classes/com/sun/tools/javac/model/JavacAnnoConstructs.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/model/JavacAnnoConstructs.java	Tue Aug 06 17:01:05 2013 -0700
@@ -108,20 +108,38 @@
     }
 
     // Helper to getAnnotation[s]
-    private static <A extends Annotation> Attribute.Compound getAttributeOnClass(ClassSymbol annotated,
-                                                                Class<A> annoType) {
+    private static <A extends Annotation> Attribute.Compound getAttributeOnClass(
+            ClassSymbol annotated,
+            final Class<A> annoType)
+    {
         boolean inherited = annoType.isAnnotationPresent(Inherited.class);
         Attribute.Compound result = null;
-        while (annotated.name != annotated.name.table.names.java_lang_Object) {
+
+        result = getAttribute(annotated, annoType);
+        if (result != null || !inherited)
+            return result;
+
+        while ((annotated = nextSupertypeToSearch(annotated)) != null) {
             result = getAttribute(annotated, annoType);
-            if (result != null || !inherited)
-                break;
-            Type sup = annotated.getSuperclass();
-            if (!sup.hasTag(CLASS) || sup.isErroneous())
-                break;
-            annotated = (ClassSymbol) sup.tsym;
+            if (result != null)
+                return result;
         }
-        return result;
+        return null; // no more supertypes to search
+    }
+
+    /**
+     * Returns the next type to search for inherited annotations or {@code null}
+     * if the next type can't be found.
+     */
+    private static ClassSymbol nextSupertypeToSearch(ClassSymbol annotated) {
+        if (annotated.name == annotated.name.table.names.java_lang_Object)
+            return null;
+
+        Type sup = annotated.getSuperclass();
+        if (!sup.hasTag(CLASS) || sup.isErroneous())
+            return null;
+
+        return (ClassSymbol) sup.tsym;
     }
 
     /**
@@ -129,8 +147,9 @@
      * annotations. This is the implementation of
      * Element.getAnnotations(Class).
      */
-    public static <A extends Annotation> A[] getAnnotations(Symbol annotated,
-                                                            Class<A> annoType) {
+    public static <A extends Annotation> A[] getAnnotationsByType(Symbol annotated,
+            Class<A> annoType)
+    {
         if (!annoType.isAnnotation())
             throw new IllegalArgumentException("Not an annotation type: "
                                                + annoType);
@@ -153,62 +172,48 @@
         }
 
         // So we have a containing type
-        String name = annoType.getName();
         String annoTypeName = annoType.getSimpleName();
         String containerTypeName = containerType.getSimpleName();
         int directIndex = -1, containerIndex = -1;
         Attribute.Compound direct = null, container = null;
-        Attribute.Compound[] rawAttributes = annotated.getRawAttributes().toArray(new Attribute.Compound[0]);
-
-        // Find directly present annotations
-        for (int i = 0; i < rawAttributes.length; i++) {
-            if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
-                directIndex = i;
-                direct = rawAttributes[i];
+        // Find directly (explicit or implicit) present annotations
+        int index = -1;
+        for (List<Attribute.Compound> list = annotated.getAnnotationMirrors();
+                !list.isEmpty();
+                list = list.tail) {
+            Attribute.Compound attribute = list.head;
+            index++;
+            if (attribute.type.tsym.flatName().contentEquals(annoTypeName)) {
+                directIndex = index;
+                direct = attribute;
             } else if(containerTypeName != null &&
-                      containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
-                containerIndex = i;
-                container = rawAttributes[i];
+                      attribute.type.tsym.flatName().contentEquals(containerTypeName)) {
+                containerIndex = index;
+                container = attribute;
             }
         }
 
         // Deal with inherited annotations
-        if (annotated.kind == Kinds.TYP &&
-                (annotated instanceof ClassSymbol)) {
-            ClassSymbol s = (ClassSymbol)annotated;
-            if (direct == null && container == null) {
-                direct = getAttributeOnClass(s, annoType);
-                container = getAttributeOnClass(s, containerType);
-
-                // both are inherited and found, put container last
-                if (direct != null && container != null) {
-                    directIndex = 0;
-                    containerIndex = 1;
-                } else if (direct != null) {
-                    directIndex = 0;
-                } else {
-                    containerIndex = 0;
-                }
-            } else if (direct == null) {
-                direct = getAttributeOnClass(s, annoType);
-                if (direct != null)
-                    directIndex = containerIndex + 1;
-            } else if (container == null) {
-                container = getAttributeOnClass(s, containerType);
-                if (container != null)
-                    containerIndex = directIndex + 1;
+        if (direct == null && container == null) {
+            if (annotated.kind == Kinds.TYP &&
+                    (annotated instanceof ClassSymbol)) {
+                ClassSymbol s = nextSupertypeToSearch((ClassSymbol)annotated);
+                if (s != null)
+                    return getAnnotationsByType(s, annoType);
             }
         }
 
         // Pack them in an array
-        Attribute[] contained0 = new Attribute[0];
+        Attribute[] contained0 = null;
         if (container != null)
             contained0 = unpackAttributes(container);
         ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
-        for (Attribute a : contained0)
-            if (a instanceof Attribute.Compound)
-                compounds = compounds.append((Attribute.Compound)a);
-        Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
+        if (contained0 != null) {
+            for (Attribute a : contained0)
+                if (a instanceof Attribute.Compound)
+                    compounds = compounds.append((Attribute.Compound)a);
+        }
+        Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[compounds.size()]);
 
         int size = (direct == null ? 0 : 1) + contained.length;
         @SuppressWarnings("unchecked") // annoType is the Class for A
@@ -298,35 +303,38 @@
         }
 
         // So we have a containing type
-        String name = annoType.getName();
         String annoTypeName = annoType.getSimpleName();
         String containerTypeName = containerType.getSimpleName();
         int directIndex = -1, containerIndex = -1;
         Attribute.Compound direct = null, container = null;
-        Attribute.Compound[] rawAttributes = annotated.getAnnotationMirrors().toArray(new Attribute.Compound[0]);
-
-        // Find directly present annotations
-        for (int i = 0; i < rawAttributes.length; i++) {
-            if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
-                directIndex = i;
-                direct = rawAttributes[i];
+        // Find directly (explicit or implicit) present annotations
+        int index = -1;
+        for (List<? extends Attribute.Compound> list = annotated.getAnnotationMirrors();
+                !list.isEmpty();
+                list = list.tail) {
+            Attribute.Compound attribute = list.head;
+            index++;
+            if (attribute.type.tsym.flatName().contentEquals(annoTypeName)) {
+                directIndex = index;
+                direct = attribute;
             } else if(containerTypeName != null &&
-                      containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
-                containerIndex = i;
-                container = rawAttributes[i];
+                      attribute.type.tsym.flatName().contentEquals(containerTypeName)) {
+                containerIndex = index;
+                container = attribute;
             }
         }
 
         // Pack them in an array
-        Attribute[] contained0 = new Attribute[0];
+        Attribute[] contained0 = null;
         if (container != null)
             contained0 = unpackAttributes(container);
         ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
-        for (Attribute a : contained0) {
-            if (a instanceof Attribute.Compound)
-                compounds = compounds.append((Attribute.Compound)a);
+        if (contained0 != null) {
+            for (Attribute a : contained0)
+                if (a instanceof Attribute.Compound)
+                    compounds = compounds.append((Attribute.Compound)a);
         }
-        Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
+        Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[compounds.size()]);
 
         int size = (direct == null ? 0 : 1) + contained.length;
         @SuppressWarnings("unchecked") // annoType is the Class for A
--- a/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java	Tue Aug 06 17:01:05 2013 -0700
@@ -4053,7 +4053,7 @@
             endPosMap = new HashMap<JCTree, Integer>();
         }
 
-        protected void storeEnd(JCTree tree, int endpos) {
+        public void storeEnd(JCTree tree, int endpos) {
             endPosMap.put(tree, errorEndPos > endpos ? errorEndPos : endpos);
         }
 
@@ -4091,7 +4091,7 @@
             super(parser);
         }
 
-        protected void storeEnd(JCTree tree, int endpos) { /* empty */ }
+        public void storeEnd(JCTree tree, int endpos) { /* empty */ }
 
         protected <T extends JCTree> T to(T t) {
             return t;
@@ -4127,14 +4127,6 @@
         }
 
         /**
-         * Store ending position for a tree, the value of which is the greater
-         * of last error position and the given ending position.
-         * @param tree   The tree.
-         * @param endpos The ending position to associate with the tree.
-         */
-        protected abstract void storeEnd(JCTree tree, int endpos);
-
-        /**
          * Store current token's ending position for a tree, the value of which
          * will be the greater of last error position and the ending position of
          * the current token.
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -905,6 +905,10 @@
 compiler.err.report.access=\
     {0} has {1} access in {2}
 
+# 0: symbol, 1: set of modifier, 2: symbol
+compiler.misc.report.access=\
+    {0} has {1} access in {2}
+
 compiler.err.ret.outside.meth=\
     return outside method
 
@@ -914,6 +918,10 @@
 compiler.err.signature.doesnt.match.intf=\
     signature does not match {0}; incompatible interfaces
 
+# 0: number, 1: number
+compiler.err.method.invoked.with.incorrect.number.arguments=\
+    method invoked with incorrect number of arguments; expected {0}, found {1}
+
 # 0: symbol, 1: symbol, 2: symbol
 compiler.err.does.not.override.abstract=\
     {0} is not abstract and does not override abstract method {1} in {2}
@@ -1069,6 +1077,10 @@
     variable {0} might not have been initialized
 
 # 0: symbol
+compiler.err.var.not.initialized.in.default.constructor=\
+    variable {0} not initialized in the default constructor
+
+# 0: symbol
 compiler.err.var.might.be.assigned.in.loop=\
     variable {0} might be assigned in loop
 
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/EndPosTable.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/EndPosTable.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, 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,10 +43,17 @@
     public int getEndPos(JCTree tree);
 
     /**
+     * Store ending position for a tree, the value of which is the greater of
+     * last error position and the given ending position.
+     * @param tree The tree.
+     * @param endpos The ending position to associate with the tree.
+     */
+    public abstract void storeEnd(JCTree tree, int endpos);
+
+    /**
      * Give an old tree and a new tree, the old tree will be replaced with
      * the new tree, the position of the new tree will be that of the old
      * tree.
-     * not exist.
      * @param oldtree a JCTree to be replaced
      * @param newtree a JCTree to be replaced with
      * @return position of the old tree or Positions.NOPOS for non-existent mapping
--- a/langtools/test/com/sun/javadoc/testCRLineSeparator/TestCRLineSeparator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/com/sun/javadoc/testCRLineSeparator/TestCRLineSeparator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2013, 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
@@ -38,7 +38,7 @@
 public class TestCRLineSeparator extends JavadocTester {
 
     //Test information.
-    private static final String BUG_ID = "4979486";
+    private static final String BUG_ID = "4979486-8014636";
 
     //Javadoc arguments.
     private static final String[] ARGS = new String[] {
@@ -47,7 +47,7 @@
 
     //Input for string search tests.
     private static final String[][] TEST = {
-        {BUG_ID + FS + "pkg" + FS + "MyClass.html", "Line 1\n Line 2"}
+        {BUG_ID + FS + "pkg" + FS + "MyClass.html", "Line 1" + NL + " Line 2"}
     };
 
     private static final String[][] NEGATED_TEST = NO_TEST;
--- a/langtools/test/com/sun/javadoc/testLeadingSpaces/LeadingSpaces.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/com/sun/javadoc/testLeadingSpaces/LeadingSpaces.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, 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,11 +23,11 @@
 
 /*
  * @test
- * @bug 4232882
+ * @bug 4232882 8014636
  * @summary Javadoc strips all of the leading spaces when the comment
  *    does not begin with a star.  This RFE allows users to
  *    begin their comment without a leading star without leading
- *    spaces striped
+ *    spaces stripped
  * @author jamieh
  * @library ../lib/
  * @build JavadocTester
@@ -37,15 +37,15 @@
 
 public class LeadingSpaces extends JavadocTester {
 
-    private static final String BUG_ID = "4232882";
+    private static final String BUG_ID = "4232882-8014636";
     private static final String[][] TEST = {
         {BUG_ID + FS + "LeadingSpaces.html",
-"        1\n" +
-"          2\n" +
-"            3\n" +
-"              4\n" +
-"                5\n" +
-"                  6\n" +
+"        1" + NL +
+"          2" + NL +
+"            3" + NL +
+"              4" + NL +
+"                5" + NL +
+"                  6" + NL +
 "                    7"}
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
--- a/langtools/test/com/sun/javadoc/testLinkTaglet/TestLinkTaglet.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/com/sun/javadoc/testLinkTaglet/TestLinkTaglet.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2013, 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,7 +23,7 @@
 
 /*
  * @test
- * @bug      4732864 6280605 7064544
+ * @bug      4732864 6280605 7064544 8014636
  * @summary  Make sure that you can link from one member to another using
  *           non-qualified name, furthermore, ensure the right one is linked.
  * @author   jamieh
@@ -36,7 +36,7 @@
 public class TestLinkTaglet extends JavadocTester {
 
     //Test information.
-    private static final String BUG_ID = "4732864-6280605-7064544";
+    private static final String BUG_ID = "4732864-6280605-7064544-8014636";
 
     //Javadoc arguments.
     private static final String[] ARGS = new String[] {
@@ -46,16 +46,16 @@
     //Input for string search tests.
     private static final String[][] TEST = {
         {BUG_ID + FS + "pkg" + FS + "C.html",
-            "Qualified Link: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>\n" +
-            " Unqualified Link1: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>\n" +
-            " Unqualified Link2: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>\n" +
-            " Qualified Link: <a href=\"../pkg/C.html#method(pkg.C.InnerC, pkg.C.InnerC2)\"><code>method(pkg.C.InnerC, pkg.C.InnerC2)</code></a>.<br/>\n" +
-            " Unqualified Link: <a href=\"../pkg/C.html#method(pkg.C.InnerC, pkg.C.InnerC2)\"><code>method(C.InnerC, C.InnerC2)</code></a>.<br/>\n" +
+            "Qualified Link: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>" + NL +
+            " Unqualified Link1: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>" + NL +
+            " Unqualified Link2: <a href=\"../pkg/C.InnerC.html\" title=\"class in pkg\"><code>C.InnerC</code></a>.<br/>" + NL +
+            " Qualified Link: <a href=\"../pkg/C.html#method(pkg.C.InnerC, pkg.C.InnerC2)\"><code>method(pkg.C.InnerC, pkg.C.InnerC2)</code></a>.<br/>" + NL +
+            " Unqualified Link: <a href=\"../pkg/C.html#method(pkg.C.InnerC, pkg.C.InnerC2)\"><code>method(C.InnerC, C.InnerC2)</code></a>.<br/>" + NL +
             " Unqualified Link: <a href=\"../pkg/C.html#method(pkg.C.InnerC, pkg.C.InnerC2)\"><code>method(InnerC, InnerC2)</code></a>.<br/>"
         },
         {BUG_ID + FS + "pkg" + FS + "C.InnerC.html",
-            "Link to member in outer class: <a href=\"../pkg/C.html#MEMBER\"><code>C.MEMBER</code></a> <br/>\n" +
-            " Link to member in inner class: <a href=\"../pkg/C.InnerC2.html#MEMBER2\"><code>C.InnerC2.MEMBER2</code></a> <br/>\n" +
+            "Link to member in outer class: <a href=\"../pkg/C.html#MEMBER\"><code>C.MEMBER</code></a> <br/>" + NL +
+            " Link to member in inner class: <a href=\"../pkg/C.InnerC2.html#MEMBER2\"><code>C.InnerC2.MEMBER2</code></a> <br/>" + NL +
             " Link to another inner class: <a href=\"../pkg/C.InnerC2.html\" title=\"class in pkg\"><code>C.InnerC2</code></a>"
         },
         {BUG_ID + FS + "pkg" + FS + "C.InnerC2.html",
--- a/langtools/test/com/sun/javadoc/testLiteralCodeInPre/TestLiteralCodeInPre.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/com/sun/javadoc/testLiteralCodeInPre/TestLiteralCodeInPre.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug      8002387
+ * @bug      8002387 8014636
  * @summary  Improve rendered HTML formatting for {@code}
  * @library  ../lib/
  * @build    JavadocTester TestLiteralCodeInPre
@@ -33,7 +33,7 @@
 public class TestLiteralCodeInPre extends JavadocTester {
 
     //Test information.
-    private static final String BUG_ID = "8002387";
+    private static final String BUG_ID = "8002387-8014636";
     private static final String OUTPUT_DIR = BUG_ID;
 
     //Javadoc arguments.
--- a/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, 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,11 +23,9 @@
 
 /*
  * @test
- * @bug      4460354
+ * @bug      4460354 8014636
  * @summary  Test to make sure that relative paths are redirected in the
  *           output so that they are not broken.
- *           NOTE: these tests have \\n instead of NL because they are user
- *           generated new lines, not Java generated.
  * @author   jamieh
  * @library  ../lib/
  * @build    JavadocTester
@@ -38,7 +36,7 @@
 public class TestRelativeLinks extends JavadocTester {
 
     //Test information.
-    private static final String BUG_ID = "4460354";
+    private static final String BUG_ID = "4460354-8014636";
 
     //Javadoc arguments.
     private static final String[] ARGS = new String[] {
@@ -58,7 +56,7 @@
         {BUG_ID + FS + "pkg" + FS + "package-summary.html",
             "<a href=\"relative-package-link.html\">relative package link</a>"},
         {BUG_ID + FS + "pkg" + FS + "C.html",
-            " <a\n" +
+            " <a" + NL +
             " href=\"relative-multi-line-link.html\">relative-multi-line-link</a>."},
 
         //These relative paths should be redirected because they are in different
@@ -74,7 +72,7 @@
         {BUG_ID + FS + "index-all.html",
             "<a href=\"./pkg/relative-package-link.html\">relative package link</a>"},
         {BUG_ID + FS + "index-all.html",
-            " <a\n" +
+            " <a" + NL +
             " href=\"./pkg/relative-multi-line-link.html\">relative-multi-line-link</a>."},
 
 
@@ -92,7 +90,7 @@
         {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "C.html",
             "<a href=\"../../pkg/relative-package-link.html\">relative package link</a>"},
         {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "C.html",
-            " <a\n" +
+            " <a" + NL +
             " href=\"../../pkg/relative-multi-line-link.html\">relative-multi-line-link</a>."},
 
         //PACKAGE OVERVIEW
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AnchorTest2.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,20 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8020313
+ * @summary doclint doesn't reset HTML anchors correctly
+ * @build DocLintTester
+ * @run main DocLintTester -ref AnchorTest2.out AnchorTest2.java AnchorTest2a.java
+ * @run main DocLintTester -ref AnchorTest2.out AnchorTest2a.java AnchorTest2.java
+ */
+
+/** */
+public class AnchorTest2 {
+    /** <a name="AnchorTest2"> </a> */
+    public void a_name_AnchorTest2() { }
+
+    /** <a name="AnchorTest2"> </a> */
+    public void a_name_AnchorTest2_already_defined() { }
+
+    /** <a name="AnchorTest2a"> </a> */
+    public void a_name_AnchorTest2a_defined_in_other_file() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AnchorTest2.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+AnchorTest2.java:15: error: anchor already defined: AnchorTest2
+    /** <a name="AnchorTest2"> </a> */
+           ^
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AnchorTest2a.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,7 @@
+/* /nodynamiccopyright/ */
+
+/**
+ * <a name="AnchorTest2a"> </a>
+ */
+public class AnchorTest2a { }
+
--- a/langtools/test/tools/doclint/BadPackageCommentTest.out	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/doclint/BadPackageCommentTest.out	Tue Aug 06 17:01:05 2013 -0700
@@ -1,3 +1,6 @@
+BadPackageCommentTest.java:13: warning: documentation comment not expected here
+package p;
+^
 BadPackageCommentTest.java:11: error: no tag name after @
  * @@@
    ^
@@ -8,3 +11,4 @@
  * @@@
      ^
 3 errors
+1 warning
--- a/langtools/test/tools/doclint/DocLintTester.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/doclint/DocLintTester.java	Tue Aug 06 17:01:05 2013 -0700
@@ -123,7 +123,7 @@
     private static final Pattern dirFileLine = Pattern.compile(
             "(?m)"                          // multi-line mode
             + "^(.*?)"                      // directory part of file name
-            + "([A-Za-z0-9.]+:[0-9]+:)");   // file name and line number
+            + "([-A-Za-z0-9.]+:[0-9]+:)");  // file name and line number
 
     String removeFileNames(String s) {
         Matcher m = dirFileLine.matcher(s);
--- a/langtools/test/tools/doclint/ReferenceTest.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/doclint/ReferenceTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,6 +1,6 @@
 /*
  * @test /nodynamiccopyright/
- * @bug 8004832
+ * @bug 8004832 8020556
  * @summary Add new doclint package
  * @build DocLintTester
  * @run main DocLintTester -Xmsgs:-reference ReferenceTest.java
@@ -48,5 +48,11 @@
      * @throws Exception description
      */
     public void exception_not_thrown() { }
+
+    /**
+     * @param <T> throwable
+     * @throws T description
+     */
+    public <T extends Throwable> void valid_throws_generic() throws T { }
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/Test.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8020664 8021215
+ * @summary doclint gives incorrect warnings on normal package statements
+ * @library ../..
+ * @build DocLintTester
+ * @run main DocLintTester -ref Test.out Test.java
+ * @compile/fail/ref=Test.javac.out -XDrawDiagnostics -Werror -Xdoclint:all Test.java
+ */
+
+/** Unexpected comment */
+package bad;
+
+/** */
+class Test { }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/Test.javac.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+Test.java:12:1: compiler.warn.proc.messager: documentation comment not expected here
+- compiler.err.warnings.and.werror
+1 error
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/Test.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+Test.java:12: warning: documentation comment not expected here
+package bad;
+^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/package-info.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,12 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8020664 8021215
+ * @summary doclint gives incorrect warnings on normal package statements
+ * @library ../..
+ * @build DocLintTester
+ * @run main DocLintTester -ref package-info.out package-info.java
+ * @compile/fail/ref=package-info.javac.out -XDrawDiagnostics -Werror -Xdoclint:all package-info.java
+ */
+
+// missing comment
+package bad;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/package-info.javac.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+package-info.java:12:1: compiler.warn.proc.messager: no comment
+- compiler.err.warnings.and.werror
+1 error
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/bad/package-info.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+package-info.java:12: warning: no comment
+package bad;
+^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/good/Test.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012, 2013, 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 /nodynamiccopyright/
+ * @bug 8020664 8021215
+ * @summary doclint gives incorrect warnings on normal package statements
+ * @library ../..
+ * @build DocLintTester
+ * @run main DocLintTester Test.java
+ * @compile -Xdoclint:all Test.java
+ */
+
+// no doc comment
+package good;
+
+/** */
+class Test { }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/packageTests/good/package-info.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012, 2013, 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 /nodynamiccopyright/
+ * @bug 8020664 8021215
+ * @summary doclint gives incorrect warnings on normal package statements
+ * @library ../..
+ * @build DocLintTester
+ * @run main DocLintTester package-info.java
+ * @compile -Xdoclint:all package-info.java
+ */
+
+/** Description. */
+package good;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/ErasureTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2013, 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 8016013
+ * @summary Compiler incorrectly treats annotated and unannotated type variable bounds as different types
+ * @compile -doe ErasureTest.java
+ */
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER })
+@interface Advanced {}
+
+class U {}
+interface I {}
+
+class ErasureTest {
+     <T extends U & @Advanced I> void TestMethod(T arg1) { }
+    public static void main(String argv[]) {
+        ErasureTest t1 = new ErasureTest(){
+            public <T extends @Advanced U & I> void TestMethod(T arg1) { }
+        };
+
+        ErasureTest t2 = new ErasureTest(){
+            public <T extends U & @Advanced I> void TestMethod(T arg1) { }
+        };
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/MethodInvokedWithWrongNumberOfArgs.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2013, 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.method.invoked.with.incorrect.number.arguments
+// options: -Xlint:-options -source 6 -target 6
+
+class MethodInvokedWithWrongNumberOfArgs {
+    static java.lang.invoke.MethodHandle getNamedMember;
+    public static Object getMember(String name, Object rec) throws Throwable {
+        return getNamedMember.invoke(rec, name);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ReportAccessFragment.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2013, 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.prob.found.req
+// key: compiler.misc.invalid.mref
+// key: compiler.misc.report.access
+
+class ReportAccessFragment {
+    void test(Object o) {
+        Runnable r = o::clone;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/VarNotIntializedInDefaultConstructor.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2013, 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.var.not.initialized.in.default.constructor
+
+class X {
+    final int j;
+}
--- a/langtools/test/tools/javac/generics/diamond/6939780/T6939780.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/generics/diamond/6939780/T6939780.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1,6 +1,6 @@
 /*
  * @test /nodynamiccopyright/
- * @bug 6939780 7020044 8009459
+ * @bug 6939780 7020044 8009459 8021338
  *
  * @summary  add a warning to detect diamond sites
  * @author mcimadamore
@@ -36,4 +36,15 @@
 
     void gw(Foo<?> fw) { }
     void gn(Foo<Number> fn) { }
+
+    static class Foo2<X> {
+        X copy(X t) {
+            return t;
+        }
+    }
+
+    void testReciever() {
+        Number s = new Foo2<Number>().copy(0);
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/jvm/T8020689.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,36 @@
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 8020689
+ * @summary Making sure the LineNumberTable entry is correctly generated for the leading method invocation in the else section
+ * @compile T8020689.java
+ * @run main T8020689
+ */
+
+public class T8020689 {
+
+    public static void main(String... args) {
+        if (args.length > 0) {
+            a();
+        } else {
+            b();
+        }
+    }
+
+    static void a() {
+    }
+
+    static void b() {
+        assertLine(15);
+    }
+
+    public static void assertLine(int expectedline) {
+        Exception e = new Exception("expected line#: " + expectedline);
+        int myline = e.getStackTrace()[2].getLineNumber();
+        if( myline != expectedline) {
+            throw new RuntimeException("Incorrect line number " +
+                    "expected: " + expectedline +
+                    ", got: " + myline, e);
+        }
+        System.out.format("Got expected line number %d correct %n", myline);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8016081/T8016081.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2013, 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 8016081
+ * @summary field initialized with lambda in annotation types doesn't compile
+ * @compile T8016081.java
+ */
+
+class T8016081 {
+    interface fint { int get(); }
+
+    @interface atype {
+        fint fld = ()->( fld == null ?0 : 1);
+    }
+
+    @atype class T {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8020804/T8020804.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2013, 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 8020804
+ * @summary javac crashes when speculative attribution infers intersection type with array component
+ * @compile T8020804.java
+ */
+
+import java.util.*;
+
+class T8020804 {
+    interface Supplier<D> {
+        D make();
+    }
+
+    void m(Object o) { }
+    void m(char[] c) { }
+
+    <C extends Collection<?>> C g(Supplier<C> sc) { return null; }
+
+    void test() {
+        m(g(LinkedList<Double>::new));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8020843/T8020843a.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8020843
+ * @summary javac crashes on accessibility check with method reference with typevar receiver
+ * @compile/fail/ref=T8020843a.out -XDrawDiagnostics T8020843a.java
+ */
+
+class T8020843a {
+    interface Function<X, Y> {
+        Y m(X x);
+    }
+
+    <T> void test(T t) {
+        Function<T, Object> ss = T::clone;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8020843/T8020843a.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,2 @@
+T8020843a.java:14:34: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.report.access: clone(), protected, java.lang.Object))
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8020843/T8020843b.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,27 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8020843
+ * @summary javac crashes on accessibility check with method reference with typevar receiver
+ * @compile/fail/ref=T8020843b.out -XDrawDiagnostics T8020843b.java
+ */
+
+class T8020843b {
+    interface Function<X, Y> {
+        Y m(X x);
+    }
+
+    interface BiFunction<X, Y, Z> {
+        Z m(X x, Y y);
+    }
+
+    Object m(int i) { return null; }
+    static Object m(String t) { return null; }
+
+    Object m2(int i) { return null; }
+    static Object m2(long t) { return null; }
+
+    static void test() {
+        Function<T8020843b, Object> f1 = T8020843b::m; //show bound case diag
+        BiFunction<T8020843b, String, Object> f2 = T8020843b::m2; //show unbound case diag
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/8020843/T8020843b.out	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,3 @@
+T8020843b.java:24:42: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbols: kindname.method, m, T8020843b,{(compiler.misc.inapplicable.method: kindname.method, T8020843b, m(int), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: T8020843b, int))),(compiler.misc.inapplicable.method: kindname.method, T8020843b, m(java.lang.String), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: T8020843b, java.lang.String)))}))
+T8020843b.java:25:52: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbols: kindname.method, m2, T8020843b,java.lang.String,{(compiler.misc.inapplicable.method: kindname.method, T8020843b, m2(int), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: java.lang.String, int))),(compiler.misc.inapplicable.method: kindname.method, T8020843b, m2(long), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: java.lang.String, long)))}))
+2 errors
--- a/langtools/test/tools/javac/lambda/MethodReference28.out	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/lambda/MethodReference28.out	Tue Aug 06 17:01:05 2013 -0700
@@ -9,6 +9,6 @@
 MethodReference28.java:46:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m3, java.lang.String, int, kindname.class, MethodReference28, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: int, java.lang.String))))
 MethodReference28.java:47:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m4, java.lang.String[], int, kindname.class, MethodReference28, (compiler.misc.varargs.argument.mismatch: (compiler.misc.inconvertible.types: int, java.lang.String))))
 MethodReference28.java:52:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m2, java.lang.Integer,java.lang.Integer, MethodReference28,int, kindname.class, MethodReference28, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: MethodReference28, java.lang.Integer))))
-MethodReference28.java:53:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m3, java.lang.String, MethodReference28,int, kindname.class, MethodReference28, (compiler.misc.arg.length.mismatch)))
+MethodReference28.java:53:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m3, java.lang.String, MethodReference28,int, kindname.class, MethodReference28, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: int, java.lang.String))))
 MethodReference28.java:54:19: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, m4, java.lang.String[], MethodReference28,int, kindname.class, MethodReference28, (compiler.misc.varargs.argument.mismatch: (compiler.misc.inconvertible.types: MethodReference28, java.lang.String))))
 13 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/positions/TreeEndPosTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2013, 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 8017216 8019422 8019421
+ * @summary verify start and end positions
+ * @run main TreeEndPosTest
+ */
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
+public class TreeEndPosTest {
+    private static JavaFileManager getJavaFileManager(JavaCompiler compiler,
+            DiagnosticCollector dc) {
+        return compiler.getStandardFileManager(dc, null, null);
+    }
+
+    static class JavaSource extends SimpleJavaFileObject {
+
+        final String source;
+        int startPos;
+        int endPos;
+
+        private JavaSource(String filename, String source) {
+            super(URI.create("myfo:/" + filename), JavaFileObject.Kind.SOURCE);
+            this.source = source;
+        }
+
+        @Override
+        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+            return source;
+        }
+
+        static JavaSource createJavaSource(String preamble, String body,
+                String postamble, String expected) {
+            JavaSource js = createJavaSource(preamble, body, postamble, -1, -1);
+            js.startPos = js.source.indexOf(expected);
+            js.endPos   = js.startPos + expected.length();
+            return js;
+        }
+
+        static JavaSource createJavaSource(String body, String expected) {
+            return createJavaSource(null, body, null, expected);
+        }
+
+        private static JavaSource createJavaSource(String preamble, String body,
+                String postamble, int start, int end) {
+            final String name = "Bug";
+            StringBuilder code = new StringBuilder();
+            if (preamble != null) {
+                code.append(preamble);
+            }
+            code.append("public class " + name + "{");
+            if (body != null) {
+                code.append(body);
+            }
+            code.append("}");
+            if (postamble != null) {
+                code.append(postamble);
+            }
+            JavaSource js = new JavaSource(name + ".java", code.toString());
+            js.startPos = start;
+            js.endPos = end;
+            return js;
+        }
+    }
+
+    public static void main(String... args) throws IOException {
+        testUninitializedVariable();
+        testMissingAnnotationValue();
+        testFinalVariableWithDefaultConstructor();
+        testFinalVariableWithConstructor();
+    }
+
+    static void testUninitializedVariable() throws IOException {
+        compile(JavaSource.createJavaSource("Object o = new A().new B(); class A { }",
+                "B()"));
+    }
+    static void testMissingAnnotationValue() throws IOException {
+        compile(JavaSource.createJavaSource("@Foo(\"vvvv\")",
+                null, "@interface Foo { }", "\"vvvv\""));
+    }
+
+    static void testFinalVariableWithDefaultConstructor() throws IOException {
+        compile(JavaSource.createJavaSource("private static final String Foo; public void bar() { }",
+                "private static final String Foo;"));
+    }
+
+    static void testFinalVariableWithConstructor() throws IOException {
+        compile(JavaSource.createJavaSource("public Bug (){} private static final String Foo; public void bar() { }",
+                "{}"));
+    }
+
+    static void compile(JavaSource src) throws IOException {
+        ByteArrayOutputStream ba = new ByteArrayOutputStream();
+        PrintWriter writer = new PrintWriter(ba);
+        File tempDir = new File(".");
+        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+        DiagnosticCollector dc = new DiagnosticCollector();
+        JavaFileManager javaFileManager = getJavaFileManager(compiler, dc);
+        List<String> options = new ArrayList<>();
+        options.add("-cp");
+        options.add(tempDir.getPath());
+        options.add("-d");
+        options.add(tempDir.getPath());
+        options.add("-XDshouldStopPolicy=GENERATE");
+
+        List<JavaFileObject> sources = new ArrayList<>();
+        sources.add(src);
+        JavaCompiler.CompilationTask task =
+                compiler.getTask(writer, javaFileManager,
+                dc, options, null,
+                sources);
+        task.call();
+        for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
+            long actualStart = diagnostic.getStartPosition();
+            long actualEnd = diagnostic.getEndPosition();
+            System.out.println("Source: " + src.source);
+            System.out.println("Diagnostic: " + diagnostic);
+            System.out.print("Start position: Expected: " + src.startPos);
+            System.out.println(", Actual: " + actualStart);
+            System.out.print("End position: Expected: " + src.endPos);
+            System.out.println(", Actual: " + actualEnd);
+            if (src.startPos != actualStart || src.endPos != actualEnd) {
+                throw new RuntimeException("error: trees don't match");
+            }
+        }
+    }
+}
--- a/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedA1Test.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedA1Test.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,12 +23,11 @@
 
 /*
  * @test
- * @bug     8004822
+ * @bug     8004822 8007961
  * @author  mnunez
  * @summary Language model api test basics for repeating annotations
  * @library /tools/javac/lib
  * @library supportingAnnotations
- * @ignore  8013407: test failures for repeating annotations
  * @build   JavacTestingAbstractProcessor ElementRepAnnoTester
  * @compile -processor ElementRepAnnoTester -proc:only
  * MixRepeatableAndOfficialContainerInheritedA1Test.java
--- a/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedB1Test.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedB1Test.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,12 +23,11 @@
 
 /*
  * @test
- * @bug     8004822
+ * @bug     8004822 8007961
  * @author  mnunez
  * @summary Language model api test basics for repeating annotations
  * @library /tools/javac/lib
  * @library supportingAnnotations
- * @ignore  8013407: test failures for repeating annotations
  * @build   JavacTestingAbstractProcessor ElementRepAnnoTester
  * @compile -processor ElementRepAnnoTester -proc:only
  * MixRepeatableAndOfficialContainerInheritedB1Test.java
--- a/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedB2Test.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/MixRepeatableAndOfficialContainerInheritedB2Test.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,12 +23,11 @@
 
 /*
  * @test
- * @bug     8004822
+ * @bug     8004822 8007961
  * @author  mnunez
  * @summary Language model api test basics for repeating annotations
  * @library /tools/javac/lib
  * @library supportingAnnotations
- * @ignore  8013407: test failures for repeating annotations
  * @build   JavacTestingAbstractProcessor ElementRepAnnoTester
  * @compile -processor ElementRepAnnoTester -proc:only
  * MixRepeatableAndOfficialContainerInheritedB2Test.java
--- a/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/RepeatableOverrideATest.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/RepeatableOverrideATest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,12 +23,11 @@
 
 /*
  * @test
- * @bug     8004822
+ * @bug     8004822 8007961
  * @author  mnunez
  * @summary Language model api test basics for repeating annotations
  * @library /tools/javac/lib
  * @library supportingAnnotations
- * @ignore  8013407: test failures for repeating annotations
  * @build   JavacTestingAbstractProcessor ElementRepAnnoTester
  * @compile -processor ElementRepAnnoTester -proc:only RepeatableOverrideATest.java
  */
--- a/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/RepeatableOverrideBTest.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/langtools/test/tools/javac/processing/model/element/repeatingAnnotations/RepeatableOverrideBTest.java	Tue Aug 06 17:01:05 2013 -0700
@@ -23,12 +23,11 @@
 
 /*
  * @test
- * @bug     8004822
+ * @bug     8004822 8007961
  * @author  mnunez
  * @summary Language model api test basics for repeating annotations
  * @library /tools/javac/lib
  * @library supportingAnnotations
- * @ignore  8013407: test failures for repeating annotations
  * @build   JavacTestingAbstractProcessor ElementRepAnnoTester
  * @compile -processor ElementRepAnnoTester -proc:only RepeatableOverrideBTest.java
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/inheritedByType/EnsureOrder.java	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2013, 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 test that order is respected when inheriting both legacy container and single anno
+ * @bug 8007961
+ * @library /tools/javac/lib
+ * @build   JavacTestingAbstractProcessor EnsureOrder
+ * @compile -processor EnsureOrder -proc:only EnsureOrder.java
+ */
+
+import java.util.Set;
+import java.lang.annotation.*;
+import javax.annotation.processing.*;
+import javax.lang.model.SourceVersion;
+import static javax.lang.model.SourceVersion.*;
+import javax.lang.model.element.*;
+import javax.lang.model.util.*;
+import static javax.lang.model.util.ElementFilter.*;
+import static javax.tools.Diagnostic.Kind.*;
+import static javax.tools.StandardLocation.*;
+import com.sun.tools.javac.util.Assert;
+
+@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE})
+@Inherited
+@Retention(RetentionPolicy.RUNTIME)
+@Repeatable(Foos.class)
+@interface Foo {
+    int value();
+}
+
+@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE})
+@Inherited
+@Retention(RetentionPolicy.RUNTIME)
+@interface Foos {
+    Foo[] value();
+}
+
+@Foos({@Foo(0), @Foo(1)}) @Foo(2)
+class Base {}
+
+class Sub extends Base {}
+
+public class EnsureOrder<@Foos({@Foo(0), @Foo(1)}) @Foo(2)T> extends JavacTestingAbstractProcessor {
+    public boolean process(Set<? extends TypeElement> annotations,
+                           RoundEnvironment roundEnv) {
+        if (!roundEnv.processingOver()) {
+            int hasRun = 0;
+            for (Element element : roundEnv.getRootElements()) {
+                Name elemName = element.getSimpleName();
+                if (elemName.contentEquals("Base")) {
+                    hasRun++;
+                    Foo[] foos = element.getAnnotationsByType(Foo.class);
+                    Assert.check(foos.length == 3);
+                    Assert.check(foos[0].value() == 0);
+                    Assert.check(foos[1].value() == 1);
+                    Assert.check(foos[2].value() == 2);
+                }
+                if (elemName.contentEquals("Sub")) {
+                    hasRun++;
+                    Foo[] foos = element.getAnnotationsByType(Foo.class);
+                    Assert.check(foos.length == 3);
+                    Assert.check(foos[0].value() == 0);
+                    Assert.check(foos[1].value() == 1);
+                    Assert.check(foos[2].value() == 2);
+                }
+                if (elemName.contentEquals("EnsureOrder")) {
+                    for (TypeParameterElement t : ((TypeElement)element).getTypeParameters()) {
+                        if (t.getSimpleName().contentEquals("T")) {
+                            hasRun++;
+                            Foo[] foos = t.getAnnotationsByType(Foo.class);
+                            Assert.check(foos.length == 3);
+                            Assert.check(foos[0].value() == 0);
+                            Assert.check(foos[1].value() == 1);
+                            Assert.check(foos[2].value() == 2);
+                        }
+                    }
+                }
+            }
+            if (hasRun != 3)
+                throw new RuntimeException("Couldn't find elements");
+        }
+        return true;
+    }
+}
--- a/nashorn/.hgtags	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/.hgtags	Tue Aug 06 17:01:05 2013 -0700
@@ -210,3 +210,4 @@
 542b7803f0389a91fab58608a0f46fac0e15d759 jdk8-b98
 10a1ab9e20a42d278aa1a89698f2a4cf5883d00d jdk8-b99
 598321c438b52d9408a2671fb3fc2b2947d0f654 jdk8-b100
+a302b05d0ee460679501dc01004f70eb395fadf5 jdk8-b101
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -152,14 +152,14 @@
     }
 
     static MethodGenerator makeStaticInitializer(final ClassVisitor cv, final String name) {
-        final int access = ACC_PUBLIC | ACC_STATIC;
+        final int access =  ACC_PUBLIC | ACC_STATIC;
         final String desc = DEFAULT_INIT_DESC;
         final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
         return new MethodGenerator(mv, access, name, desc);
     }
 
     static MethodGenerator makeConstructor(final ClassVisitor cv) {
-        final int access = ACC_PUBLIC;
+        final int access = 0;
         final String name = INIT;
         final String desc = DEFAULT_INIT_DESC;
         final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -25,6 +25,7 @@
 
 package jdk.nashorn.internal.tools.nasgen;
 
+import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
 import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
 import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
 import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC;
@@ -80,7 +81,7 @@
     byte[] getClassBytes() {
         // new class extensing from ScriptObject
         final String superClass = (constructor != null)? SCRIPTFUNCTIONIMPL_TYPE : SCRIPTOBJECT_TYPE;
-        cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, className, null, superClass, null);
+        cw.visit(V1_7, ACC_FINAL, className, null, superClass, null);
         if (memberCount > 0) {
             // add fields
             emitFields();
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -25,6 +25,7 @@
 
 package jdk.nashorn.internal.tools.nasgen;
 
+import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
 import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
 import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
 import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
@@ -60,7 +61,7 @@
 
     byte[] getClassBytes() {
         // new class extensing from ScriptObject
-        cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, className, null, PROTOTYPEOBJECT_TYPE, null);
+        cw.visit(V1_7, ACC_FINAL | ACC_SUPER, className, null, PROTOTYPEOBJECT_TYPE, null);
         if (memberCount > 0) {
             // add fields
             emitFields();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/exclude/exclude_list.txt	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<excludeList>
+</excludeList>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/exclude/exclude_list_cc.txt	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<excludeList>
+  <test id="JDK-8014647.js" />
+  <test id="javaclassoverrides.js" />
+</excludeList>
--- a/nashorn/make/build.xml	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/make/build.xml	Tue Aug 06 17:01:05 2013 -0700
@@ -47,17 +47,22 @@
     <!-- check if testng.jar is avaiable -->
     <available property="testng.available" file="${file.reference.testng.jar}"/>
 
-	<!-- enable/disable make code coverage -->
-	<condition property="cc.enabled">
-		<istrue value="${make.code.coverage}" />
-	</condition>
+    <!-- enable/disable make code coverage -->
+    <condition property="cc.enabled">
+        <istrue value="${make.code.coverage}" />
+    </condition>
+
+    <!-- exclude tests in exclude lists -->
+    <condition property="exclude.list" value="./exclude/exclude_list_cc.txt" else="./exclude/exclude_list.txt">
+      <istrue value="${make.code.coverage}" />
+    </condition>
   </target>
 
   <target name="init" depends="init-conditions, init-cc">
 
-	<!-- extends jvm args -->
-	<property name="run.test.jvmargs" value="${run.test.jvmargs.main}  ${run.test.cc.jvmargs}"/>
-	<property name="run.test.jvmargs.octane" value="${run.test.jvmargs.octane.main}  ${run.test.cc.jvmargs}" />
+    <!-- extends jvm args -->
+    <property name="run.test.jvmargs" value="${run.test.jvmargs.main}  ${run.test.cc.jvmargs}"/>
+    <property name="run.test.jvmargs.octane" value="${run.test.jvmargs.octane.main}  ${run.test.cc.jvmargs}" />
 
     <echo message="run.test.jvmargs=${run.test.jvmargs}"/>
     <echo message="run.test.jvmargs.octane=${run.test.jvmargs.octane}"/>
@@ -262,6 +267,11 @@
 grant codeBase "file:/${basedir}/test/script/basic/JDK-8010946-privileged.js" {
     permission java.util.PropertyPermission "java.security.policy", "read";
 };
+
+grant codeBase "file:/${basedir}/test/script/basic/classloader.js" {
+    permission java.lang.RuntimePermission "nashorn.JavaReflection";
+};
+
     </echo>
 
     <replace file="${build.dir}/nashorn.policy"><replacetoken>\</replacetoken><replacevalue>/</replacevalue></replace>    <!--hack for Windows - to make URLs with normal path separators -->
@@ -284,19 +294,6 @@
   </target>
 
   <target name="test" depends="jar, check-testng, check-external-tests, compile-test, generate-policy-file" if="testng.available">
-    <java classname="${nashorn.shell.tool}" fork="true" dir="${test.script.dir}/representations" output="${build.dir}/output1.log" error="${build.dir}/err.log">
-      <jvmarg line="${ext.class.path}"/>
-      <jvmarg line="-Dnashorn.fields.dual=true"/>
-      <arg value="NASHORN-592a.js"/>
-    </java>
-    <java classname="${nashorn.shell.tool}" fork="true" dir="${test.script.dir}/representations" output="${build.dir}/output2.log" error="${build.dir}/err.log">
-      <jvmarg line="${ext.class.path}"/>
-      <arg value="NASHORN-592a.js"/>
-    </java>
-    <condition property="representation-ok">
-      <filesmatch file1="${build.dir}/output1.log" file2="${build.dir}/output2.log"/>
-    </condition>
-    <fail unless="representation-ok">Representation test failed - output differs!</fail>
     <fileset id="test.classes" dir="${build.test.classes.dir}">
       <include name="**/api/javaaccess/*Test.class"/>
       <include name="**/api/scripting/*Test.class"/>
@@ -316,6 +313,7 @@
         <propertyref prefix="test-sys-prop."/>
         <mapper from="test-sys-prop.*" to="*" type="glob"/>
       </propertyset>
+      <sysproperty key="test.js.excludes.file" value="${exclude.list}"/>
       <classpath>
           <pathelement path="${run.test.classpath}"/>
       </classpath>
--- a/nashorn/make/code_coverage.xml	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/make/code_coverage.xml	Tue Aug 06 17:01:05 2013 -0700
@@ -132,7 +132,7 @@
       <arg value="-exclude"/>
       <arg value="com\.oracle\.nashorn\.runtime\.ScriptRuntime*"/>
       <arg value="-exclude"/>
-      <arg value="jdk\.nashorn\.internal\.javaadapters*"/>
+      <arg value="jdk\.nashorn\.javaadapters*"/>
       <arg value="-exclude"/>
       <arg value="jdk\.nashorn\.internal\.objects\.annotations*"/>
       <arg value="-exclude"/>
--- a/nashorn/make/project.properties	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/make/project.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -223,7 +223,6 @@
 run.test.user.country=TR
 
 #  -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintNMethods
-# add '-Dtest.js.outofprocess' to run each test in a new sub-process
 run.test.jvmargs.main=-server -Xmx${run.test.xmx} -XX:+TieredCompilation -ea -Dfile.encoding=UTF-8 -Duser.language=${run.test.user.language} -Duser.country=${run.test.user.country}
 
 #-XX:+HeapDumpOnOutOfMemoryError -XX:-UseCompressedKlassPointers -XX:+PrintHeapAtGC -XX:ClassMetaspaceSize=300M  
@@ -231,6 +230,9 @@
 
 run.test.jvmsecurityargs=-Xverify:all -Djava.security.properties=${basedir}/make/java.security.override -Djava.security.manager -Djava.security.policy=${basedir}/build/nashorn.policy
 
+# VM options for script tests with @fork option
+test-sys-prop.test.fork.jvm.options=${run.test.jvmargs.main} ${run.test.jvmsecurityargs}
+
 # path of rhino.jar for benchmarks
 rhino.jar=
 
--- a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java	Tue Aug 06 17:01:05 2013 -0700
@@ -303,14 +303,13 @@
     private static MethodHandle unreflectSafely(AccessibleObject m) {
         if(m instanceof Method) {
             final Method reflMethod = (Method)m;
-            final MethodHandle handle = SafeUnreflector.unreflect(reflMethod);
+            final MethodHandle handle = Lookup.PUBLIC.unreflect(reflMethod);
             if(Modifier.isStatic(reflMethod.getModifiers())) {
                 return StaticClassIntrospector.editStaticMethodHandle(handle);
             }
             return handle;
         }
-        return StaticClassIntrospector.editConstructorMethodHandle(SafeUnreflector.unreflectConstructor(
-                (Constructor<?>)m));
+        return StaticClassIntrospector.editConstructorMethodHandle(Lookup.PUBLIC.unreflectConstructor((Constructor<?>)m));
     }
 
     private static DynamicMethod mergeMethods(SingleDynamicMethod method, DynamicMethod existing, Class<?> clazz, String name) {
--- a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java	Tue Aug 06 17:01:05 2013 -0700
@@ -92,6 +92,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Map;
+import jdk.internal.dynalink.support.Lookup;
 
 /**
  * Base for classes that expose class field and method information to an {@link AbstractJavaLinker}. There are
@@ -160,11 +161,11 @@
 
 
     MethodHandle unreflectGetter(Field field) {
-        return editMethodHandle(SafeUnreflector.unreflectGetter(field));
+        return editMethodHandle(Lookup.PUBLIC.unreflectGetter(field));
     }
 
     MethodHandle unreflectSetter(Field field) {
-        return editMethodHandle(SafeUnreflector.unreflectSetter(field));
+        return editMethodHandle(Lookup.PUBLIC.unreflectSetter(field));
     }
 
     /**
--- a/nashorn/src/jdk/internal/dynalink/beans/SafeUnreflector.java	Fri Jun 28 16:26:54 2013 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,156 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, 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.
- */
-
-/*
- * This file is available under and governed by the GNU General Public
- * License version 2 only, as published by the Free Software Foundation.
- * However, the following notice accompanied the original version of this
- * file, and Oracle licenses the original version of this file under the BSD
- * license:
- */
-/*
-   Copyright 2009-2013 Attila Szegedi
-
-   Licensed under both the Apache License, Version 2.0 (the "Apache License")
-   and the BSD License (the "BSD License"), with licensee being free to
-   choose either of the two at their discretion.
-
-   You may not use this file except in compliance with either the Apache
-   License or the BSD License.
-
-   If you choose to use this file in compliance with the Apache License, the
-   following notice applies to you:
-
-       You may obtain a copy of the Apache License at
-
-           http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing, software
-       distributed under the License is distributed on an "AS IS" BASIS,
-       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-       implied. See the License for the specific language governing
-       permissions and limitations under the License.
-
-   If you choose to use this file in compliance with the BSD License, the
-   following notice applies to you:
-
-       Redistribution and use in source and binary forms, with or without
-       modification, are permitted provided that the following conditions are
-       met:
-       * Redistributions of source code must retain the above copyright
-         notice, this list of conditions and the following disclaimer.
-       * 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.
-       * Neither the name of the copyright holder nor the names of
-         contributors may be used to endorse or promote products derived from
-         this software without specific prior written permission.
-
-       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-       IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER
-       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.
-*/
-
-package jdk.internal.dynalink.beans;
-
-import java.lang.invoke.MethodHandle;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import jdk.internal.dynalink.beans.sandbox.Unreflector;
-
-/**
- * Provides lookup of unreflected method handles through delegation to an instance of {@link SafeUnreflectorImpl}. If
- * Dynalink is run as trusted code, the delegate class is loaded into an isolated zero-permissions protection domain,
- * serving as a firebreak against an accidental privilege escalation downstream.
- */
-final class SafeUnreflector {
-    private static final String UNREFLECTOR_IMPL_CLASS_NAME = "jdk.internal.dynalink.beans.SafeUnreflectorImpl";
-    private static final Unreflector impl = createImpl();
-
-    private SafeUnreflector() {
-    }
-
-    /**
-     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)}, converting any encountered
-     * {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param m the method to unreflect
-     * @return the unreflected method handle.
-     */
-    static MethodHandle unreflect(Method m) {
-        return impl.unreflect(m);
-    }
-
-    /**
-     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)}, converting any encountered
-     * {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param f the field for which a getter is unreflected
-     * @return the unreflected field getter handle.
-     */
-    static MethodHandle unreflectGetter(Field f) {
-        return impl.unreflectGetter(f);
-    }
-
-    /**
-     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter(Field)}, converting any encountered
-     * {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param f the field for which a setter is unreflected
-     * @return the unreflected field setter handle.
-     */
-    static MethodHandle unreflectSetter(Field f) {
-        return impl.unreflectSetter(f);
-    }
-
-    static MethodHandle unreflectConstructor(Constructor<?> c) {
-        return impl.unreflectConstructor(c);
-    }
-
-    private static Unreflector createImpl() {
-        final Class<?> unreflectorImplClass = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
-            @Override
-            public Class<?> run() {
-                return SandboxClassLoader.loadClass(UNREFLECTOR_IMPL_CLASS_NAME);
-            }
-        });
-        try {
-            return (Unreflector)unreflectorImplClass.newInstance();
-        } catch(InstantiationException | IllegalAccessException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-    }
-}
--- a/nashorn/src/jdk/internal/dynalink/beans/SafeUnreflectorImpl.java	Fri Jun 28 16:26:54 2013 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,146 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, 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.
- */
-
-/*
- * This file is available under and governed by the GNU General Public
- * License version 2 only, as published by the Free Software Foundation.
- * However, the following notice accompanied the original version of this
- * file, and Oracle licenses the original version of this file under the BSD
- * license:
- */
-/*
-   Copyright 2009-2013 Attila Szegedi
-
-   Licensed under both the Apache License, Version 2.0 (the "Apache License")
-   and the BSD License (the "BSD License"), with licensee being free to
-   choose either of the two at their discretion.
-
-   You may not use this file except in compliance with either the Apache
-   License or the BSD License.
-
-   If you choose to use this file in compliance with the Apache License, the
-   following notice applies to you:
-
-       You may obtain a copy of the Apache License at
-
-           http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing, software
-       distributed under the License is distributed on an "AS IS" BASIS,
-       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-       implied. See the License for the specific language governing
-       permissions and limitations under the License.
-
-   If you choose to use this file in compliance with the BSD License, the
-   following notice applies to you:
-
-       Redistribution and use in source and binary forms, with or without
-       modification, are permitted provided that the following conditions are
-       met:
-       * Redistributions of source code must retain the above copyright
-         notice, this list of conditions and the following disclaimer.
-       * 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.
-       * Neither the name of the copyright holder nor the names of
-         contributors may be used to endorse or promote products derived from
-         this software without specific prior written permission.
-
-       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-       IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER
-       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.
-*/
-
-package jdk.internal.dynalink.beans;
-
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import jdk.internal.dynalink.beans.sandbox.Unreflector;
-
-/**
- * Performs lookup of unreflected method handles by delegating to {@link MethodHandles#lookup()} using itself as the
- * lookup class. When Dynalink runs as trusted code, this class is loaded into an isolated zero-permissions protection
- * domain to stop any accidental privilege escalation.
- */
-final class SafeUnreflectorImpl implements Unreflector {
-
-    SafeUnreflectorImpl() {
-    }
-
-    @Override
-    public MethodHandle unreflect(Method m) {
-        try {
-            return MethodHandles.lookup().unreflect(m);
-        } catch(IllegalAccessException e) {
-            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect method " + m);
-            ee.initCause(e);
-            throw ee;
-        }
-    }
-
-    @Override
-    public MethodHandle unreflectGetter(Field f) {
-        try {
-            return MethodHandles.lookup().unreflectGetter(f);
-        } catch(IllegalAccessException e) {
-            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect getter for field " + f);
-            ee.initCause(e);
-            throw ee;
-        }
-    }
-
-    @Override
-    public MethodHandle unreflectSetter(Field f) {
-        try {
-            return MethodHandles.lookup().unreflectSetter(f);
-        } catch(IllegalAccessException e) {
-            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect setter for field " + f);
-            ee.initCause(e);
-            throw ee;
-        }
-    }
-
-    @Override
-    public MethodHandle unreflectConstructor(Constructor<?> c) {
-        try {
-            return MethodHandles.lookup().unreflectConstructor(c);
-        } catch(IllegalAccessException e) {
-            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect constructor " + c);
-            ee.initCause(e);
-            throw ee;
-        }
-    }
-}
--- a/nashorn/src/jdk/internal/dynalink/beans/SandboxClassLoader.java	Fri Jun 28 16:26:54 2013 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,228 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, 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.
- */
-
-/*
- * This file is available under and governed by the GNU General Public
- * License version 2 only, as published by the Free Software Foundation.
- * However, the following notice accompanied the original version of this
- * file, and Oracle licenses the original version of this file under the BSD
- * license:
- */
-/*
-   Copyright 2009-2013 Attila Szegedi
-
-   Licensed under both the Apache License, Version 2.0 (the "Apache License")
-   and the BSD License (the "BSD License"), with licensee being free to
-   choose either of the two at their discretion.
-
-   You may not use this file except in compliance with either the Apache
-   License or the BSD License.
-
-   If you choose to use this file in compliance with the Apache License, the
-   following notice applies to you:
-
-       You may obtain a copy of the Apache License at
-
-           http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing, software
-       distributed under the License is distributed on an "AS IS" BASIS,
-       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-       implied. See the License for the specific language governing
-       permissions and limitations under the License.
-
-   If you choose to use this file in compliance with the BSD License, the
-   following notice applies to you:
-
-       Redistribution and use in source and binary forms, with or without
-       modification, are permitted provided that the following conditions are
-       met:
-       * Redistributions of source code must retain the above copyright
-         notice, this list of conditions and the following disclaimer.
-       * 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.
-       * Neither the name of the copyright holder nor the names of
-         contributors may be used to endorse or promote products derived from
-         this software without specific prior written permission.
-
-       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-       IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER
-       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.
-*/
-
-package jdk.internal.dynalink.beans;
-
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
-import static jdk.internal.org.objectweb.asm.Opcodes.ASM4;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.Permissions;
-import java.security.ProtectionDomain;
-import java.security.SecureClassLoader;
-import java.security.SecureRandom;
-import jdk.internal.org.objectweb.asm.ClassReader;
-import jdk.internal.org.objectweb.asm.ClassVisitor;
-import jdk.internal.org.objectweb.asm.ClassWriter;
-import jdk.internal.org.objectweb.asm.MethodVisitor;
-
-/**
- * A utility class that can load a class with specified name into an isolated zero-permissions protection domain. It can
- * be used to load classes that perform security-sensitive operations with no privileges at all, therefore ensuring such
- * operations will only succeed if they would require no permissions, as well as to make sure that if these operations
- * bind some part of the security execution context to their results, the bound security context is completely
- * unprivileged. Such measures serve as firebreaks against accidental privilege escalation.
- */
-final class SandboxClassLoader {
-    private final String className;
-    private final String randomizedClassName;
-
-    private SandboxClassLoader(String className) {
-        this.className = className;
-        final String simpleClassName = className.substring(className.lastIndexOf('.') + 1);
-        this.randomizedClassName = "randomPackage" + Long.toHexString(new SecureRandom().nextLong()) + "." + simpleClassName;
-    }
-
-    /**
-     * Load the named class into a zero-permissions protection domain. Even if the class is already loaded into the
-     * Dynalink's class loader, an independent class is created from the same bytecode, thus the returned class will
-     * never be identical with the one that might already be loaded. The class to be loaded is supposed to be package
-     * private and have no public constructors. This is not a functional requirement, but it is enforced to ensure that
-     * the original class was made adequately inaccessible. The returned class will be public and its constructors will
-     * be changed to public. The only permission given to the returned class will be
-     * {@code accessClassInPackage.jdk.internal.dynalink.beans.sandbox}. That package should be used solely to define
-     * SPI interfaces implemented by the loaded class.
-     * @param className the fully qualified name of the class to load
-     * @return the loaded class, renamed to a random package, made public, its constructors made public, and lacking any
-     * permissions except access to the sandbox package.
-     * @throws SecurityException if the calling code lacks the {@code createClassLoader} runtime permission. This
-     * normally means that Dynalink itself is running as untrusted code, and whatever functionality was meant to be
-     * isolated into an unprivileged class is likely okay to be used directly too.
-     */
-    static Class<?> loadClass(String className) throws SecurityException {
-        return new SandboxClassLoader(className).loadClass();
-    }
-
-    private Class<?> loadClass() throws SecurityException {
-        final ClassLoader loader = createClassLoader();
-        try {
-            final Class<?> clazz = Class.forName(randomizedClassName, true, loader);
-            // Sanity check to ensure we didn't accidentally pick up the class from elsewhere
-            if(clazz.getClassLoader() != loader) {
-                throw new AssertionError(randomizedClassName + " was loaded from a different class loader");
-            }
-            return clazz;
-        } catch(ClassNotFoundException e) {
-            throw new AssertionError(e);
-        }
-    }
-
-    private ClassLoader createClassLoader() throws SecurityException {
-        final String lclassName = this.randomizedClassName;
-        // We deliberately override loadClass instead of findClass so that we don't give a chance to finding this
-        // class already loaded anywhere else. We use this class' loader as the parent class loader as the loaded class
-        // needs to be able to access implemented interfaces from the sandbox package.
-        return new SecureClassLoader(getClass().getClassLoader()) {
-            @Override
-            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
-                if(name.equals(lclassName)) {
-                    final byte[] bytes = getClassBytes();
-                    // Define the class with a protection domain that grants (almost) no permissions.
-                    Class<?> clazz = defineClass(name, bytes, 0, bytes.length, createMinimalPermissionsDomain());
-                    if(resolve) {
-                        resolveClass(clazz);
-                    }
-                    return clazz;
-                }
-
-                final int i = name.lastIndexOf('.');
-                if (i != -1) {
-                    final SecurityManager sm = System.getSecurityManager();
-                    if (sm != null) {
-                        sm.checkPackageAccess(name.substring(0, i));
-                    }
-                }
-                return super.loadClass(name, resolve);
-            }
-        };
-    }
-
-    /**
-     * Create a no-permissions protection domain. Except, it's not really a no-permissions protection domain, since we
-     * need to give the protection domain the permission to access the sandbox package where the interop interfaces are
-     * defined.
-     * @return a new (almost) no-permission protection domain.
-     */
-    private static ProtectionDomain createMinimalPermissionsDomain() {
-        final Permissions p = new Permissions();
-        p.add(new RuntimePermission("accessClassInPackage.jdk.internal.dynalink.beans.sandbox"));
-        return new ProtectionDomain(null, p);
-    }
-
-    private byte[] getClassBytes() {
-        try(final InputStream in = getClass().getResourceAsStream("/" + className.replace('.', '/') + ".class")) {
-            final ClassReader cr = new ClassReader(in);
-            final ClassWriter cw = new ClassWriter(cr, 0);
-            cr.accept(new ClassVisitor(ASM4, cw) {
-                @Override
-                public void visit(int version, int access, String name, String signature, String superName,
-                        String[] interfaces) {
-                    // Rename the class to its random name, and make it public (otherwise we won't be able to
-                    // instantiate it). The privileged template class is package-private.
-                    if((access & ACC_PUBLIC) != 0) {
-                        throw new IllegalArgumentException("Class " + className + " must be package-private");
-                    }
-                    super.visit(version, access | ACC_PUBLIC, randomizedClassName.replace('.', '/'),
-                            signature, superName, interfaces);
-                }
-
-                @Override
-                public MethodVisitor visitMethod(int access, String name, String desc, String signature,
-                        String[] exceptions) {
-                    // Make the constructor(s) public (otherwise we won't be able to instantiate the class). The
-                    // privileged template's constructor(s) should not be public.
-                    final boolean isCtor = "<init>".equals(name);
-                    if(isCtor && ((access & ACC_PUBLIC) != 0)) {
-                        throw new IllegalArgumentException("Class " + className + " must have no public constructors");
-                    }
-                    return super.visitMethod(isCtor ? (access | ACC_PUBLIC) : access, name, desc, signature,
-                            exceptions);
-                }
-            }, 0);
-            return cw.toByteArray();
-        } catch(IOException e) {
-            throw new RuntimeException(e);
-        }
-    }
-}
--- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java	Tue Aug 06 17:01:05 2013 -0700
@@ -132,7 +132,9 @@
                 return new SimpleDynamicMethod(StaticClassIntrospector.editConstructorMethodHandle(
                         boundArrayCtor.asType(boundArrayCtor.type().changeReturnType(clazz))), clazz, "<init>");
             }
-
+            if(CheckRestrictedPackage.isRestrictedClass(clazz)) {
+                return null;
+            }
             return createDynamicMethod(Arrays.asList(clazz.getConstructors()), clazz, "<init>");
         }
 
--- a/nashorn/src/jdk/internal/dynalink/beans/sandbox/Unreflector.java	Fri Jun 28 16:26:54 2013 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, 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.
- */
-
-/*
- * This file is available under and governed by the GNU General Public
- * License version 2 only, as published by the Free Software Foundation.
- * However, the following notice accompanied the original version of this
- * file, and Oracle licenses the original version of this file under the BSD
- * license:
- */
-/*
-   Copyright 2009-2013 Attila Szegedi
-
-   Licensed under both the Apache License, Version 2.0 (the "Apache License")
-   and the BSD License (the "BSD License"), with licensee being free to
-   choose either of the two at their discretion.
-
-   You may not use this file except in compliance with either the Apache
-   License or the BSD License.
-
-   If you choose to use this file in compliance with the Apache License, the
-   following notice applies to you:
-
-       You may obtain a copy of the Apache License at
-
-           http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing, software
-       distributed under the License is distributed on an "AS IS" BASIS,
-       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-       implied. See the License for the specific language governing
-       permissions and limitations under the License.
-
-   If you choose to use this file in compliance with the BSD License, the
-   following notice applies to you:
-
-       Redistribution and use in source and binary forms, with or without
-       modification, are permitted provided that the following conditions are
-       met:
-       * Redistributions of source code must retain the above copyright
-         notice, this list of conditions and the following disclaimer.
-       * 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.
-       * Neither the name of the copyright holder nor the names of
-         contributors may be used to endorse or promote products derived from
-         this software without specific prior written permission.
-
-       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-       IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER
-       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.
-*/
-
-package jdk.internal.dynalink.beans.sandbox;
-
-import java.lang.invoke.MethodHandle;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-
-/**
- * Interface for creating unreflected method handles. This class is public for implementation purposes and is not part
- * of any supported API.
- */
-public interface Unreflector {
-    /**
-     * Performs similarly to {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)} for some lookup object,
-     * also converting any encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param m the method to unreflect
-     * @return the unreflected method handle.
-     */
-    public MethodHandle unreflect(Method m);
-
-    /**
-     * Performs similarly to {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)} for some lookup
-     * object, also converting any encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param f the field for which a getter is unreflected
-     * @return the unreflected field getter handle.
-     */
-    public MethodHandle unreflectGetter(Field f);
-
-    /**
-     * Performs similarly to {@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter(Field)} for some lookup
-     * object, also converting any encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param f the field for which a setter is unreflected
-     * @return the unreflected field setter handle.
-     */
-    public MethodHandle unreflectSetter(Field f);
-
-    /**
-     * Performs similarly to {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)} for some
-     * lookup object, also converting any encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
-     *
-     * @param c the constructor to unreflect
-     * @return the unreflected constructor handle.
-     */
-    public MethodHandle unreflectConstructor(Constructor<?> c);
-
-}
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Tue Aug 06 17:01:05 2013 -0700
@@ -40,6 +40,9 @@
 import java.security.PrivilegedAction;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
+import java.text.MessageFormat;
+import java.util.Locale;
+import java.util.ResourceBundle;
 import javax.script.AbstractScriptEngine;
 import javax.script.Bindings;
 import javax.script.Compilable;
@@ -79,6 +82,28 @@
     // default options passed to Nashorn Options object
     private static final String[] DEFAULT_OPTIONS = new String[] { "-scripting", "-doe" };
 
+    private static final String MESSAGES_RESOURCE = "jdk.nashorn.api.scripting.resources.Messages";
+
+    // Without do privileged, under security manager messages can not be loaded.
+    private static final ResourceBundle MESSAGES_BUNDLE;
+    static {
+        MESSAGES_BUNDLE = AccessController.doPrivileged(
+        new PrivilegedAction<ResourceBundle>() {
+            @Override
+            public ResourceBundle run() {
+                return ResourceBundle.getBundle(MESSAGES_RESOURCE, Locale.getDefault());
+            }
+        });
+    }
+
+    private static String getMessage(final String msgId, final String... args) {
+        try {
+            return new MessageFormat(MESSAGES_BUNDLE.getString(msgId)).format(args);
+        } catch (final java.util.MissingResourceException e) {
+            throw new RuntimeException("no message resource found for message id: "+ msgId);
+        }
+    }
+
     NashornScriptEngine(final NashornScriptEngineFactory factory, final ClassLoader appLoader) {
         this(factory, DEFAULT_OPTIONS, appLoader);
     }
@@ -176,43 +201,63 @@
     }
 
     @Override
-    public Object invokeMethod(final Object self, final String name, final Object... args)
+    public Object invokeMethod(final Object thiz, final String name, final Object... args)
             throws ScriptException, NoSuchMethodException {
-        if (self == null) {
-            throw new IllegalArgumentException("script object can not be null");
+        if (thiz == null) {
+            throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
         }
-        return invokeImpl(self, name, args);
+        return invokeImpl(thiz, name, args);
     }
 
-    private <T> T getInterfaceInner(final Object self, final Class<T> clazz) {
+    private <T> T getInterfaceInner(final Object thiz, final Class<T> clazz) {
         if (clazz == null || !clazz.isInterface()) {
-            throw new IllegalArgumentException("interface Class expected");
+            throw new IllegalArgumentException(getMessage("interface.class.expected"));
         }
 
         // perform security access check as early as possible
         final SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
             if (! Modifier.isPublic(clazz.getModifiers())) {
-                throw new SecurityException("attempt to implement non-public interfce: " + clazz);
+                throw new SecurityException(getMessage("implementing.non.public.interface", clazz.getName()));
             }
             Context.checkPackageAccess(clazz.getName());
         }
 
-        final ScriptObject realSelf;
-        final ScriptObject ctxtGlobal = getNashornGlobalFrom(context);
-        if(self == null) {
-            realSelf = ctxtGlobal;
-        } else if (!(self instanceof ScriptObject)) {
-            realSelf = (ScriptObject)ScriptObjectMirror.unwrap(self, ctxtGlobal);
-        } else {
-            realSelf = (ScriptObject)self;
+        ScriptObject realSelf = null;
+        ScriptObject realGlobal = null;
+        if(thiz == null) {
+            // making interface out of global functions
+            realSelf = realGlobal = getNashornGlobalFrom(context);
+        } else if (thiz instanceof ScriptObjectMirror) {
+            final ScriptObjectMirror mirror = (ScriptObjectMirror)thiz;
+            realSelf = mirror.getScriptObject();
+            realGlobal = mirror.getHomeGlobal();
+            if (! realGlobal.isOfContext(nashornContext)) {
+                throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
+            }
+        } else if (thiz instanceof ScriptObject) {
+            // called from script code.
+            realSelf = (ScriptObject)thiz;
+            realGlobal = Context.getGlobal();
+            if (realGlobal == null) {
+                throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
+            }
+
+            if (! realGlobal.isOfContext(nashornContext)) {
+                throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
+            }
+        }
+
+        if (realSelf == null) {
+            throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
         }
 
         try {
-            final ScriptObject oldGlobal = getNashornGlobal();
+            final ScriptObject oldGlobal = Context.getGlobal();
+            final boolean globalChanged = (oldGlobal != realGlobal);
             try {
-                if(oldGlobal != ctxtGlobal) {
-                    setNashornGlobal(ctxtGlobal);
+                if (globalChanged) {
+                    Context.setGlobal(realGlobal);
                 }
 
                 if (! isInterfaceImplemented(clazz, realSelf)) {
@@ -220,8 +265,8 @@
                 }
                 return clazz.cast(JavaAdapterFactory.getConstructor(realSelf.getClass(), clazz).invoke(realSelf));
             } finally {
-                if(oldGlobal != ctxtGlobal) {
-                    setNashornGlobal(oldGlobal);
+                if (globalChanged) {
+                    Context.setGlobal(oldGlobal);
                 }
             }
         } catch(final RuntimeException|Error e) {
@@ -237,11 +282,11 @@
     }
 
     @Override
-    public <T> T getInterface(final Object self, final Class<T> clazz) {
-        if (self == null) {
-            throw new IllegalArgumentException("script object can not be null");
+    public <T> T getInterface(final Object thiz, final Class<T> clazz) {
+        if (thiz == null) {
+            throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
         }
-        return getInterfaceInner(self, clazz);
+        return getInterfaceInner(thiz, clazz);
     }
 
     // These are called from the "engine.js" script
@@ -357,50 +402,48 @@
     }
 
     private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
-        final ScriptObject oldGlobal     = getNashornGlobal();
-        final ScriptObject ctxtGlobal    = getNashornGlobalFrom(context);
-        final boolean globalChanged = (oldGlobal != ctxtGlobal);
+        name.getClass(); // null check
 
-        Object self = globalChanged? ScriptObjectMirror.wrap(selfObject, oldGlobal) : selfObject;
-
-        try {
-            if (globalChanged) {
-                setNashornGlobal(ctxtGlobal);
+        ScriptObjectMirror selfMirror = null;
+        if (selfObject instanceof ScriptObjectMirror) {
+            selfMirror = (ScriptObjectMirror)selfObject;
+            if (! selfMirror.getHomeGlobal().isOfContext(nashornContext)) {
+                throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
+            }
+        } else if (selfObject instanceof ScriptObject) {
+            // invokeMethod called from script code - in which case we may get 'naked' ScriptObject
+            // Wrap it with oldGlobal to make a ScriptObjectMirror for the same.
+            final ScriptObject oldGlobal = Context.getGlobal();
+            if (oldGlobal == null) {
+                throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
             }
 
-            ScriptObject sobj;
-            Object       value = null;
-
-            self = ScriptObjectMirror.unwrap(self, ctxtGlobal);
-
-            // FIXME: should convert when self is not ScriptObject
-            if (self instanceof ScriptObject) {
-                sobj = (ScriptObject)self;
-                value = sobj.get(name);
-            } else if (self == null) {
-                self  = ctxtGlobal;
-                sobj  = ctxtGlobal;
-                value = sobj.get(name);
+            if (! oldGlobal.isOfContext(nashornContext)) {
+                throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
             }
 
-            if (value instanceof ScriptFunction) {
-                final Object res;
-                try {
-                    final Object[] modArgs = globalChanged? ScriptObjectMirror.wrapArray(args, oldGlobal) : args;
-                    res = ScriptRuntime.checkAndApply((ScriptFunction)value, self, ScriptObjectMirror.unwrapArray(modArgs, ctxtGlobal));
-                } catch (final Exception e) {
-                    throwAsScriptException(e);
-                    throw new AssertionError("should not reach here");
+            selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(selfObject, oldGlobal);
+        } else if (selfObject == null) {
+            // selfObject is null => global function call
+            final ScriptObject ctxtGlobal = getNashornGlobalFrom(context);
+            selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(ctxtGlobal, ctxtGlobal);
+        }
+
+        if (selfMirror != null) {
+            try {
+                return ScriptObjectMirror.translateUndefined(selfMirror.call(name, args));
+            } catch (final Exception e) {
+                final Throwable cause = e.getCause();
+                if (cause instanceof NoSuchMethodException) {
+                    throw (NoSuchMethodException)cause;
                 }
-                return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(res, ctxtGlobal));
-            }
-
-            throw new NoSuchMethodException(name);
-        } finally {
-            if (globalChanged) {
-                setNashornGlobal(oldGlobal);
+                throwAsScriptException(e);
+                throw new AssertionError("should not reach here");
             }
         }
+
+        // Non-script object passed as selfObject
+        throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
     }
 
     private Object evalImpl(final char[] buf, final ScriptContext ctxt) throws ScriptException {
@@ -411,12 +454,12 @@
         if (script == null) {
             return null;
         }
-        final ScriptObject oldGlobal = getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final ScriptObject ctxtGlobal = getNashornGlobalFrom(ctxt);
         final boolean globalChanged = (oldGlobal != ctxtGlobal);
         try {
             if (globalChanged) {
-                setNashornGlobal(ctxtGlobal);
+                Context.setGlobal(ctxtGlobal);
             }
 
             setContextVariables(ctxt);
@@ -426,7 +469,7 @@
             throw new AssertionError("should not reach here");
         } finally {
             if (globalChanged) {
-                setNashornGlobal(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
     }
@@ -469,12 +512,12 @@
     }
 
     private ScriptFunction compileImpl(final Source source, final ScriptContext ctxt) throws ScriptException {
-        final ScriptObject oldGlobal = getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final ScriptObject ctxtGlobal = getNashornGlobalFrom(ctxt);
         final boolean globalChanged = (oldGlobal != ctxtGlobal);
         try {
             if (globalChanged) {
-                setNashornGlobal(ctxtGlobal);
+                Context.setGlobal(ctxtGlobal);
             }
 
             return nashornContext.compileScript(source, ctxtGlobal);
@@ -483,7 +526,7 @@
             throw new AssertionError("should not reach here");
         } finally {
             if (globalChanged) {
-                setNashornGlobal(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
     }
@@ -502,19 +545,4 @@
         }
         return true;
     }
-
-    // don't make this public!!
-    static ScriptObject getNashornGlobal() {
-        return Context.getGlobal();
-    }
-
-    static void setNashornGlobal(final ScriptObject newGlobal) {
-        AccessController.doPrivileged(new PrivilegedAction<Void>() {
-            @Override
-            public Void run() {
-               Context.setGlobal(newGlobal);
-               return null;
-            }
-        });
-    }
 }
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Tue Aug 06 17:01:05 2013 -0700
@@ -79,17 +79,17 @@
     // JSObject methods
     @Override
     public Object call(final String functionName, final Object... args) {
-        final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
             if (globalChanged) {
-                NashornScriptEngine.setNashornGlobal(global);
+                Context.setGlobal(global);
             }
 
             final Object val = functionName == null? sobj : sobj.get(functionName);
             if (! (val instanceof ScriptFunction)) {
-                throw new RuntimeException("No such function " + ((functionName != null)? functionName : ""));
+                throw new NoSuchMethodException("No such function " + ((functionName != null)? functionName : ""));
             }
 
             final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args;
@@ -100,19 +100,19 @@
             throw new RuntimeException(t);
         } finally {
             if (globalChanged) {
-                NashornScriptEngine.setNashornGlobal(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
     }
 
     @Override
     public Object newObject(final String functionName, final Object... args) {
-        final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
             if (globalChanged) {
-                NashornScriptEngine.setNashornGlobal(global);
+                Context.setGlobal(global);
             }
 
             final Object val = functionName == null? sobj : sobj.get(functionName);
@@ -128,7 +128,7 @@
             throw new RuntimeException(t);
         } finally {
             if (globalChanged) {
-                NashornScriptEngine.setNashornGlobal(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
     }
@@ -272,7 +272,7 @@
 
     @Override
     public Object put(final String key, final Object value) {
-        final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         return inGlobal(new Callable<Object>() {
             @Override public Object call() {
@@ -284,7 +284,7 @@
 
     @Override
     public void putAll(final Map<? extends String, ? extends Object> map) {
-        final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         inGlobal(new Callable<Object>() {
             @Override public Object call() {
@@ -535,7 +535,7 @@
      * @return wrapped object
      */
     public static Object wrap(final Object obj, final ScriptObject homeGlobal) {
-        return (obj instanceof ScriptObject) ? new ScriptObjectMirror((ScriptObject)obj, homeGlobal) : obj;
+        return (obj instanceof ScriptObject && homeGlobal != null) ? new ScriptObjectMirror((ScriptObject)obj, homeGlobal) : obj;
     }
 
     /**
@@ -599,24 +599,32 @@
     // package-privates below this.
 
     ScriptObjectMirror(final ScriptObject sobj, final ScriptObject global) {
+        assert sobj != null : "ScriptObjectMirror on null!";
+        assert global != null : "null global for ScriptObjectMirror!";
+
         this.sobj = sobj;
         this.global = global;
     }
 
+    // accessors for script engine
     ScriptObject getScriptObject() {
         return sobj;
     }
 
+    ScriptObject getHomeGlobal() {
+        return global;
+    }
+
     static Object translateUndefined(Object obj) {
         return (obj == ScriptRuntime.UNDEFINED)? null : obj;
     }
 
     // internals only below this.
     private <V> V inGlobal(final Callable<V> callable) {
-        final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
+        final ScriptObject oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         if (globalChanged) {
-            NashornScriptEngine.setNashornGlobal(global);
+            Context.setGlobal(global);
         }
         try {
             return callable.call();
@@ -626,9 +634,8 @@
             throw new AssertionError("Cannot happen", e);
         } finally {
             if (globalChanged) {
-                NashornScriptEngine.setNashornGlobal(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/nashorn/api/scripting/resources/Messages.properties	Tue Aug 06 17:01:05 2013 -0700
@@ -0,0 +1,32 @@
+#
+# Copyright (c) 2010, 2013, 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.
+#
+
+thiz.cannot.be.null=script object 'this' for getMethod, getInterface calls can not be null
+interface.class.expected=interface Class expected in getInterface
+interface.on.non.script.object=getInterface cannot be called on non-script object
+no.current.nashorn.global=no current Global instance for nashorn
+implementing.non.public.interface=Cannot implement non-public interface: {0}
+script.object.from.another.engine=Script object belongs to another script engine
+
--- a/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/api/scripting/resources/engine.js	Tue Aug 06 17:01:05 2013 -0700
@@ -39,12 +39,20 @@
     }
 });
 
-function print(str) {
+function print() {
     var writer = context.getWriter();
     if (! (writer instanceof java.io.PrintWriter)) {
         writer = new java.io.PrintWriter(writer);
     }
-    writer.println(String(str));
+    
+    var buf = new java.lang.StringBuilder();
+    for (var i = 0; i < arguments.length; i++) {
+        if (i != 0) {
+            buf.append(' ');
+        }
+        buf.append(String(arguments[i]));
+    }
+    writer.println(buf.toString());
 }
 
 /**
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1143,22 +1143,23 @@
         final Type elementType = arrayType.getElementType();
 
         if (units != null) {
-            final MethodEmitter savedMethod = method;
+            final MethodEmitter savedMethod     = method;
+            final FunctionNode  currentFunction = lc.getCurrentFunction();
 
             for (final ArrayUnit arrayUnit : units) {
                 unit = lc.pushCompileUnit(arrayUnit.getCompileUnit());
 
                 final String className = unit.getUnitClassName();
-                final String name      = lc.getCurrentFunction().uniqueName(SPLIT_PREFIX.symbolName());
-                final String signature = methodDescriptor(type, Object.class, ScriptFunction.class, ScriptObject.class, type);
+                final String name      = currentFunction.uniqueName(SPLIT_PREFIX.symbolName());
+                final String signature = methodDescriptor(type, ScriptFunction.class, Object.class, ScriptObject.class, type);
 
                 final MethodEmitter me = unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature);
                 method = lc.pushMethodEmitter(me);
 
-                method.setFunctionNode(lc.getCurrentFunction());
+                method.setFunctionNode(currentFunction);
                 method.begin();
 
-                fixScopeSlot();
+                fixScopeSlot(currentFunction);
 
                 method.load(arrayType, SPLIT_ARRAY_ARG.slot());
 
@@ -1171,10 +1172,10 @@
                 method = lc.popMethodEmitter(me);
 
                 assert method == savedMethod;
+                method.loadCompilerConstant(CALLEE);
+                method.swap();
                 method.loadCompilerConstant(THIS);
                 method.swap();
-                method.loadCompilerConstant(CALLEE);
-                method.swap();
                 method.loadCompilerConstant(SCOPE);
                 method.swap();
                 method.invokestatic(className, name, signature);
@@ -1680,11 +1681,8 @@
         method = lc.pushMethodEmitter(splitEmitter);
         method.setFunctionNode(fn);
 
-        if (fn.needsCallee()) {
-            caller.loadCompilerConstant(CALLEE);
-        } else {
-            caller.loadNull();
-        }
+        assert fn.needsCallee() : "split function should require callee";
+        caller.loadCompilerConstant(CALLEE);
         caller.loadCompilerConstant(THIS);
         caller.loadCompilerConstant(SCOPE);
         if (needsArguments) {
@@ -1694,18 +1692,18 @@
         caller.storeCompilerConstant(RETURN);
 
         method.begin();
+        // Copy scope to its target slot as first thing because the original slot could be used by return symbol.
+        fixScopeSlot(fn);
 
         method.loadUndefined(fn.getReturnType());
         method.storeCompilerConstant(RETURN);
 
-        fixScopeSlot();
-
         return true;
     }
 
-    private void fixScopeSlot() {
-        if (lc.getCurrentFunction().compilerConstant(SCOPE).getSlot() != SCOPE.slot()) {
-            // TODO hack to move the scope to the expected slot (that's needed because split methods reuse the same slots as the root method)
+    private void fixScopeSlot(final FunctionNode functionNode) {
+        // TODO hack to move the scope to the expected slot (needed because split methods reuse the same slots as the root method)
+        if (functionNode.compilerConstant(SCOPE).getSlot() != SCOPE.slot()) {
             method.load(Type.typeFor(ScriptObject.class), SCOPE.slot());
             method.storeCompilerConstant(SCOPE);
         }
@@ -1756,7 +1754,7 @@
             caller.ifne(breakLabel);
             //has to be zero
             caller.label(new Label("split_return"));
-            method.loadCompilerConstant(RETURN);
+            caller.loadCompilerConstant(RETURN);
             caller._return(lc.getCurrentFunction().getReturnType());
             caller.label(breakLabel);
         } else {
@@ -1787,6 +1785,11 @@
             caller.label(breakLabel);
         }
 
+        // If split has a return and caller is itself a split method it needs to propagate the return.
+        if (hasReturn) {
+            caller.setHasReturn();
+        }
+
         return splitNode;
     }
 
--- a/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/FinalizeTypes.java	Tue Aug 06 17:01:05 2013 -0700
@@ -649,8 +649,8 @@
     }
 
     /**
-     * A symbol (and {@link Property}) can be tagged as "may be primitive". This is
-     * used a hint for dual fields that it is even worth it to try representing this
+     * A symbol (and {@link jdk.nashorn.internal.runtime.Property}) can be tagged as "may be primitive".
+     * This is used a hint for dual fields that it is even worth it to try representing this
      * field as something other than java.lang.Object.
      *
      * @param node node in which to tag symbols as primitive
@@ -856,7 +856,7 @@
      * if the expression type changes.
      *
      * Assignments use their lhs as node symbol, and in this case we can't modify
-     * it. Then {@link CodeGenerator#Store} needs to do an explicit conversion.
+     * it. Then {@link CodeGenerator.Store} needs to do an explicit conversion.
      * This is happens very rarely.
      *
      * @param node
--- a/nashorn/src/jdk/nashorn/internal/codegen/Label.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Label.java	Tue Aug 06 17:01:05 2013 -0700
@@ -105,6 +105,18 @@
         Stack copy() {
             return new Stack(data, sp);
         }
+
+        @Override
+        public String toString() {
+            final StringBuilder builder = new StringBuilder("[");
+            for (int i = 0; i < sp; i++) {
+                builder.append(data[i]);
+                if (i < sp - 1) {
+                    builder.append(", ");
+                }
+            }
+            return builder.append("]").toString();
+        }
     }
 
     /** Name of this label */
--- a/nashorn/src/jdk/nashorn/internal/codegen/Lower.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Lower.java	Tue Aug 06 17:01:05 2013 -0700
@@ -88,8 +88,6 @@
 
     /**
      * Constructor.
-     *
-     * @param compiler the compiler
      */
     Lower() {
         super(new BlockLexicalContext() {
@@ -307,8 +305,8 @@
 
         final IdentNode exception = new IdentNode(token, finish, lc.getCurrentFunction().uniqueName("catch_all"));
 
-        final Block catchBody = new Block(token, finish, new ThrowNode(lineNumber, token, finish, new IdentNode(exception), ThrowNode.IS_SYNTHETIC_RETHROW)).
-                setIsTerminal(lc, true); //ends with throw, so terminal
+        final Block catchBody = new Block(token, finish, new ThrowNode(lineNumber, token, finish, new IdentNode(exception), ThrowNode.IS_SYNTHETIC_RETHROW));
+        assert catchBody.isTerminal(); //ends with throw, so terminal
 
         final CatchNode catchAllNode  = new CatchNode(lineNumber, token, finish, new IdentNode(exception), null, catchBody, CatchNode.IS_SYNTHETIC_RETHROW);
         final Block     catchAllBlock = new Block(token, finish, catchAllNode);
@@ -330,13 +328,12 @@
     /**
      * Splice finally code into all endpoints of a trynode
      * @param tryNode the try node
-     * @param list of rethrowing throw nodes from synthetic catch blocks
+     * @param rethrows list of rethrowing throw nodes from synthetic catch blocks
      * @param finallyBody the code in the original finally block
      * @return new try node after splicing finally code (same if nop)
      */
     private Node spliceFinally(final TryNode tryNode, final List<ThrowNode> rethrows, final Block finallyBody) {
         assert tryNode.getFinallyBody() == null;
-        final int            finish = tryNode.getFinish();
 
         final TryNode newTryNode = (TryNode)tryNode.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
             final List<Node> insideTry = new ArrayList<>();
@@ -404,7 +401,7 @@
                     if (!isTerminal(newStatements)) {
                         newStatements.add(endpoint);
                     }
-                    return BlockStatement.createReplacement(endpoint, finish, newStatements);
+                    return BlockStatement.createReplacement(endpoint, tryNode.getFinish(), newStatements);
                 }
                 return endpoint;
             }
@@ -466,7 +463,7 @@
         if (tryNode.getCatchBlocks().isEmpty()) {
             newTryNode = tryNode.setFinallyBody(null);
         } else {
-            Block outerBody = new Block(tryNode.getToken(), tryNode.getFinish(), new ArrayList<Statement>(Arrays.asList(tryNode.setFinallyBody(null))));
+            Block outerBody = new Block(tryNode.getToken(), tryNode.getFinish(), tryNode.setFinallyBody(null));
             newTryNode = tryNode.setBody(outerBody).setCatchBlocks(null);
         }
 
--- a/nashorn/src/jdk/nashorn/internal/codegen/MethodEmitter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/MethodEmitter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1281,8 +1281,12 @@
     }
 
     MethodEmitter registerReturn() {
+        setHasReturn();
+        return this;
+    }
+
+    void setHasReturn() {
         this.hasReturn = true;
-        return this;
     }
 
     /**
--- a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -65,7 +65,7 @@
 
         final int      length       = keys.size();
         final Object[] presetValues = new Object[propertyMap.size()];
-        final Class    clazz        = JO.class;
+        final Class<?> clazz        = JO.class;
 
         // Compute constant values
         for (int i = 0; i < length; i++) {
--- a/nashorn/src/jdk/nashorn/internal/codegen/SplitMethodEmitter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/SplitMethodEmitter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -77,15 +77,15 @@
         }
 
         if (lc.isExternalTarget(splitNode, label)) {
-             externalTargets.add(label);
-             return externalTargets.size() - 1;
-         }
-         return -1;
+            externalTargets.add(label);
+            return externalTargets.size() - 1;
+        }
+        return -1;
     }
 
     @Override
     MethodEmitter registerReturn() {
-        super.registerReturn();
+        setHasReturn();
         loadCompilerConstant(SCOPE);
         checkcast(Scope.class);
         load(0);
--- a/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Splitter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -96,6 +96,10 @@
         long weight = WeighNodes.weigh(functionNode);
         final boolean top = fn.isProgram(); //compiler.getFunctionNode() == outermost;
 
+        // We know that our LexicalContext is empty outside the call to functionNode.accept(this) below,
+        // so we can pass null to all methods expecting a LexicalContext parameter.
+        assert lc.isEmpty() : "LexicalContext not empty";
+
         if (weight >= SPLIT_THRESHOLD) {
             LOG.finest("Splitting '", functionNode.getName(), "' as its weight ", weight, " exceeds split threshold ", SPLIT_THRESHOLD);
             functionNode = (FunctionNode)functionNode.accept(this);
@@ -103,11 +107,12 @@
             if (functionNode.isSplit()) {
                 // Weight has changed so weigh again, this time using block weight cache
                 weight = WeighNodes.weigh(functionNode, weightCache);
-                functionNode = functionNode.setBody(lc, functionNode.getBody().setNeedsScope(lc));
+                functionNode = functionNode.setBody(null, functionNode.getBody().setNeedsScope(null));
             }
 
             if (weight >= SPLIT_THRESHOLD) {
-                functionNode = functionNode.setBody(lc, splitBlock(functionNode.getBody(), functionNode));
+                functionNode = functionNode.setBody(null, splitBlock(functionNode.getBody(), functionNode));
+                functionNode = functionNode.setFlag(null, FunctionNode.IS_SPLIT);
                 weight = WeighNodes.weigh(functionNode.getBody(), weightCache);
             }
         }
@@ -116,10 +121,10 @@
 
         if (top) {
             assert outermostCompileUnit != null : "outermost compile unit is null";
-            functionNode = functionNode.setCompileUnit(lc, outermostCompileUnit);
+            functionNode = functionNode.setCompileUnit(null, outermostCompileUnit);
             outermostCompileUnit.addWeight(weight + WeighNodes.FUNCTION_WEIGHT);
         } else {
-            functionNode = functionNode.setCompileUnit(lc, findUnit(weight));
+            functionNode = functionNode.setCompileUnit(null, findUnit(weight));
         }
 
         final Block body = functionNode.getBody();
@@ -138,11 +143,11 @@
                 return split;
             }
         });
-        functionNode = functionNode.setBody(lc, newBody);
+        functionNode = functionNode.setBody(null, newBody);
 
         assert functionNode.getCompileUnit() != null;
 
-        return functionNode.setState(lc, CompilationState.SPLIT);
+        return functionNode.setState(null, CompilationState.SPLIT);
     }
 
     private static List<FunctionNode> directChildren(final FunctionNode functionNode) {
@@ -179,7 +184,6 @@
      * @return new weight for the resulting block.
      */
     private Block splitBlock(final Block block, final FunctionNode function) {
-        lc.setFlag(lc.getCurrentFunction(), FunctionNode.IS_SPLIT);
 
         final List<Statement> splits = new ArrayList<>();
         List<Statement> statements = new ArrayList<>();
@@ -255,8 +259,10 @@
         // been split already, so weigh again before splitting.
         long weight = WeighNodes.weigh(block, weightCache);
         if (weight >= SPLIT_THRESHOLD) {
-            newBlock = splitBlock(block, lc.getFunction(block));
+            final FunctionNode currentFunction = lc.getCurrentFunction();
+            newBlock = splitBlock(block, currentFunction);
             weight   = WeighNodes.weigh(newBlock, weightCache);
+            lc.setFlag(currentFunction, FunctionNode.IS_SPLIT);
         }
         weightCache.put(newBlock, weight);
         return newBlock;
@@ -289,7 +295,7 @@
                 final Node element = value[postset];
 
                 weight = WeighNodes.weigh(element);
-                totalWeight += weight;
+                totalWeight += WeighNodes.AASTORE_WEIGHT + weight;
 
                 if (totalWeight >= SPLIT_THRESHOLD) {
                     final CompileUnit unit = compiler.findUnit(totalWeight - weight);
--- a/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/codegen/WeighNodes.java	Tue Aug 06 17:01:05 2013 -0700
@@ -68,24 +68,25 @@
     /*
      * Weight constants.
      */
-            static final long FUNCTION_WEIGHT  = 40;
-    private static final long ACCESS_WEIGHT    = 4;
-    private static final long ADD_WEIGHT       = 10;
-    private static final long BREAK_WEIGHT     = 1;
-    private static final long CALL_WEIGHT      = 10;
-    private static final long CATCH_WEIGHT     = 10;
-    private static final long CONTINUE_WEIGHT  = 1;
-    private static final long IF_WEIGHT        = 2;
-    private static final long LITERAL_WEIGHT   = 10;
-    private static final long LOOP_WEIGHT      = 4;
-    private static final long NEW_WEIGHT       = 6;
-    private static final long FUNC_EXPR_WEIGHT = 20;
-    private static final long RETURN_WEIGHT    = 2;
-    private static final long SPLIT_WEIGHT     = 40;
-    private static final long SWITCH_WEIGHT    = 8;
-    private static final long THROW_WEIGHT     = 2;
-    private static final long VAR_WEIGHT       = 40;
-    private static final long WITH_WEIGHT      = 8;
+    static final long FUNCTION_WEIGHT  = 40;
+    static final long AASTORE_WEIGHT   = 2;
+    static final long ACCESS_WEIGHT    = 4;
+    static final long ADD_WEIGHT       = 10;
+    static final long BREAK_WEIGHT     = 1;
+    static final long CALL_WEIGHT      = 10;
+    static final long CATCH_WEIGHT     = 10;
+    static final long CONTINUE_WEIGHT  = 1;
+    static final long IF_WEIGHT        = 2;
+    static final long LITERAL_WEIGHT   = 10;
+    static final long LOOP_WEIGHT      = 4;
+    static final long NEW_WEIGHT       = 6;
+    static final long FUNC_EXPR_WEIGHT = 20;
+    static final long RETURN_WEIGHT    = 2;
+    static final long SPLIT_WEIGHT     = 40;
+    static final long SWITCH_WEIGHT    = 8;
+    static final long THROW_WEIGHT     = 2;
+    static final long VAR_WEIGHT       = 40;
+    static final long WITH_WEIGHT      = 8;
 
     /** Accumulated weight. */
     private long weight;
@@ -210,6 +211,7 @@
 
             if (units == null) {
                 for (final int postset : postsets) {
+                    weight += AASTORE_WEIGHT;
                     final Node element = value[postset];
 
                     if (element != null) {
--- a/nashorn/src/jdk/nashorn/internal/ir/Block.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/Block.java	Tue Aug 06 17:01:05 2013 -0700
@@ -33,10 +33,14 @@
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+
 import jdk.nashorn.internal.codegen.Label;
+import jdk.nashorn.internal.codegen.types.Type;
 import jdk.nashorn.internal.ir.annotations.Immutable;
 import jdk.nashorn.internal.ir.visitor.NodeVisitor;
 
+import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
+
 /**
  * IR representation for a list of statements.
  */
@@ -89,13 +93,13 @@
         this.symbols    = new LinkedHashMap<>();
         this.entryLabel = new Label("block_entry");
         this.breakLabel = new Label("block_break");
-        this.flags     =  0;
+        final int len = statements.length;
+        this.flags = (len > 0 && statements[len - 1].hasTerminalFlags()) ? IS_TERMINAL : 0;
     }
 
     /**
      * Constructor
      *
-     * @param lineNumber line number
      * @param token      token
      * @param finish     finish
      * @param statements statements
@@ -213,6 +217,19 @@
         return isTerminal ? setFlag(lc, IS_TERMINAL) : clearFlag(lc, IS_TERMINAL);
     }
 
+    /**
+     * Set the type of the return symbol in this block if present.
+     * @param returnType the new type
+     * @return this block
+     */
+    public Block setReturnType(final Type returnType) {
+        final Symbol symbol = getExistingSymbol(RETURN.symbolName());
+        if (symbol != null) {
+            symbol.setTypeOverride(returnType);
+        }
+        return this;
+    }
+
     @Override
     public boolean isTerminal() {
         return getFlag(IS_TERMINAL);
--- a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java	Tue Aug 06 17:01:05 2013 -0700
@@ -540,12 +540,13 @@
     /**
      * Check if this function's generated Java method needs a {@code callee} parameter. Functions that need access to
      * their parent scope, functions that reference themselves, and non-strict functions that need an Arguments object
-     * (since it exposes {@code arguments.callee} property) will need to have a callee parameter.
+     * (since it exposes {@code arguments.callee} property) will need to have a callee parameter. We also return true
+     * for split functions to make sure symbols slots are the same in the main and split methods.
      *
      * @return true if the function's generated Java method needs a {@code callee} parameter.
      */
     public boolean needsCallee() {
-        return needsParentScope() || needsSelfSymbol() || (needsArguments() && !isStrict());
+        return needsParentScope() || needsSelfSymbol() || isSplit() || (needsArguments() && !isStrict());
     }
 
     /**
@@ -816,6 +817,7 @@
         if (this.returnType == returnType) {
             return this;
         }
+        final Type type = Type.widest(this.returnType, returnType.isObject() ? Type.OBJECT : returnType);
         return Node.replaceInLexicalContext(
             lc,
             this,
@@ -824,12 +826,10 @@
                 lastToken,
                 flags,
                 name,
-                Type.widest(this.returnType, returnType.isObject() ?
-                    Type.OBJECT :
-                    returnType),
+                type,
                 compileUnit,
                 compilationState,
-                body,
+                body.setReturnType(type),
                 parameters,
                 snapshot,
                 hints));
--- a/nashorn/src/jdk/nashorn/internal/ir/IdentNode.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/IdentNode.java	Tue Aug 06 17:01:05 2013 -0700
@@ -153,14 +153,27 @@
     }
 
     /**
-     * We can only override type if the symbol lives in the scope, otherwise
-     * it is strongly determined by the local variable already allocated
+     * We can only override type if the symbol lives in the scope, as otherwise
+     * it is strongly determined by the local variable already allocated.
+     *
+     * <p>We also return true if the symbol represents the return value of a function with a
+     * non-generic return type as in this case we need to propagate the type instead of
+     * converting to object, for example if the symbol is used as the left hand side of an
+     * assignment such as in the code below.</p>
+     *
+     * <pre>{@code
+     *   try {
+     *     return 2;
+     *   } finally {
+     *     return 3;
+     *   }
+     * }</pre>
      *
      * @return true if can have callsite type
      */
     @Override
     public boolean canHaveCallSiteType() {
-        return getSymbol() != null && getSymbol().isScope();
+        return getSymbol() != null && (getSymbol().isScope() || getSymbol().isNonGenericReturn());
     }
 
     /**
--- a/nashorn/src/jdk/nashorn/internal/ir/LexicalContext.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/LexicalContext.java	Tue Aug 06 17:01:05 2013 -0700
@@ -350,10 +350,12 @@
      * @return the innermost function in the context.
      */
     public FunctionNode getCurrentFunction() {
-        if (isEmpty()) {
-            return null;
+        for (int i = sp - 1; i >= 0; i--) {
+            if (stack[i] instanceof FunctionNode) {
+                return (FunctionNode) stack[i];
+            }
         }
-        return new NodeIterator<>(FunctionNode.class).next();
+        return null;
     }
 
     /**
--- a/nashorn/src/jdk/nashorn/internal/ir/Symbol.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/Symbol.java	Tue Aug 06 17:01:05 2013 -0700
@@ -35,6 +35,8 @@
 import jdk.nashorn.internal.runtime.Debug;
 import jdk.nashorn.internal.runtime.options.Options;
 
+import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
+
 /**
  * Maps a name to specific data.
  */
@@ -442,6 +444,14 @@
     }
 
     /**
+     * Check if this symbol represents a return value with a known non-generic type.
+     * @return true if specialized return value
+     */
+    public boolean isNonGenericReturn() {
+        return getName().equals(RETURN.symbolName()) && type != Type.OBJECT;
+    }
+
+    /**
      * Check if this symbol is a function parameter of known
      * narrowest type
      * @return true if parameter
--- a/nashorn/src/jdk/nashorn/internal/ir/debug/ASTWriter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/ir/debug/ASTWriter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -102,7 +102,7 @@
             preorder.add(node);
         }
 
-        final boolean isReference = field != null && field.getAnnotation(Reference.class) != null;
+        final boolean isReference = field != null && field.isAnnotationPresent(Reference.class);
 
         Class<?> clazz = node.getClass();
         String   type  = clazz.getName();
@@ -183,7 +183,7 @@
                 append('\n');
 
             for (final Field child : children) {
-                if (child.getAnnotation(Ignore.class) != null) {
+                if (child.isAnnotationPresent(Ignore.class)) {
                     continue;
                 }
 
--- a/nashorn/src/jdk/nashorn/internal/objects/BoundScriptFunctionImpl.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/BoundScriptFunctionImpl.java	Tue Aug 06 17:01:05 2013 -0700
@@ -35,7 +35,7 @@
  * must track their {@code [[TargetFunction]]} property for purposes of correctly implementing {@code [[HasInstance]]};
  * see {@link ScriptFunction#isInstance(ScriptObject)}.
  */
-class BoundScriptFunctionImpl extends ScriptFunctionImpl {
+final class BoundScriptFunctionImpl extends ScriptFunctionImpl {
     private final ScriptFunction targetFunction;
 
     BoundScriptFunctionImpl(ScriptFunctionData data, ScriptFunction targetFunction) {
--- a/nashorn/src/jdk/nashorn/internal/objects/Global.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java	Tue Aug 06 17:01:05 2013 -0700
@@ -63,6 +63,7 @@
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.ScriptingFunctions;
 import jdk.nashorn.internal.runtime.Source;
+import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.InvokeByName;
 import jdk.nashorn.internal.scripts.JO;
 
@@ -411,18 +412,33 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
+    // performs initialization checks for Global constructor and returns the
+    // PropertyMap, if everything is fine.
+    private static PropertyMap checkAndGetMap(final Context context) {
+        // security check first
+        final SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(new RuntimePermission("nashorn.newGlobal"));
+        }
+
+        // null check on context
+        context.getClass();
+
+        /*
+         * Duplicate global's map and use it. This way the initial Map filled
+         * by nasgen (referenced from static field in this class) is retained
+         * 'as is' (as that one is process wide singleton.
+         */
+        return $nasgenmap$.duplicate();
+    }
+
     /**
      * Constructor
      *
      * @param context the context
      */
     public Global(final Context context) {
-        /*
-         * Duplicate global's map and use it. This way the initial Map filled
-         * by nasgen (referenced from static field in this class) is retained
-         * 'as is' (as that one is process wide singleton.
-         */
-        super($nasgenmap$.duplicate());
+        super(checkAndGetMap(context));
         this.setContext(context);
         this.setIsScope();
 
@@ -533,7 +549,8 @@
             if (hint == String.class) {
 
                 final Object toString = TO_STRING.getGetter().invokeExact(sobj);
-                if (toString instanceof ScriptFunction) {
+
+                if (Bootstrap.isCallable(toString)) {
                     final Object value = TO_STRING.getInvoker().invokeExact(toString, sobj);
                     if (JSType.isPrimitive(value)) {
                         return value;
@@ -541,7 +558,7 @@
                 }
 
                 final Object valueOf = VALUE_OF.getGetter().invokeExact(sobj);
-                if (valueOf instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(valueOf)) {
                     final Object value = VALUE_OF.getInvoker().invokeExact(valueOf, sobj);
                     if (JSType.isPrimitive(value)) {
                         return value;
@@ -552,7 +569,7 @@
 
             if (hint == Number.class) {
                 final Object valueOf = VALUE_OF.getGetter().invokeExact(sobj);
-                if (valueOf instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(valueOf)) {
                     final Object value = VALUE_OF.getInvoker().invokeExact(valueOf, sobj);
                     if (JSType.isPrimitive(value)) {
                         return value;
@@ -560,7 +577,7 @@
                 }
 
                 final Object toString = TO_STRING.getGetter().invokeExact(sobj);
-                if (toString instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(toString)) {
                     final Object value = TO_STRING.getInvoker().invokeExact(toString, sobj);
                     if (JSType.isPrimitive(value)) {
                         return value;
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java	Tue Aug 06 17:01:05 2013 -0700
@@ -360,7 +360,7 @@
             final ScriptObject sobj = (ScriptObject)obj;
             try {
                 final Object join = JOIN.getGetter().invokeExact(sobj);
-                if (join instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(join)) {
                     return JOIN.getInvoker().invokeExact(join, sobj);
                 }
             } catch (final RuntimeException | Error e) {
@@ -396,7 +396,7 @@
                         final ScriptObject sobj           = (ScriptObject)val;
                         final Object       toLocaleString = TO_LOCALE_STRING.getGetter().invokeExact(sobj);
 
-                        if (toLocaleString instanceof ScriptFunction) {
+                        if (Bootstrap.isCallable(toLocaleString)) {
                             sb.append((String)TO_LOCALE_STRING.getInvoker().invokeExact(toLocaleString, sobj));
                         } else {
                             throw typeError("not.a.function", "toLocaleString");
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java	Tue Aug 06 17:01:05 2013 -0700
@@ -44,9 +44,9 @@
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.PropertyMap;
 import jdk.nashorn.internal.runtime.ScriptEnvironment;
-import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
+import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.InvokeByName;
 
 /**
@@ -862,7 +862,7 @@
 
         try {
             final Object func = TO_ISO_STRING.getGetter().invokeExact(sobj);
-            if (func instanceof ScriptFunction) {
+            if (Bootstrap.isCallable(func)) {
                 return TO_ISO_STRING.getInvoker().invokeExact(func, sobj, key);
             }
             throw typeError("not.a.function", ScriptRuntime.safeToString(func));
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java	Tue Aug 06 17:01:05 2013 -0700
@@ -189,7 +189,7 @@
             if (value instanceof ScriptObject) {
                 final ScriptObject svalue = (ScriptObject)value;
                 final Object toJSON = TO_JSON.getGetter().invokeExact(svalue);
-                if (toJSON instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(toJSON)) {
                     value = TO_JSON.getInvoker().invokeExact(toJSON, svalue, key);
                 }
             }
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java	Tue Aug 06 17:01:05 2013 -0700
@@ -55,7 +55,6 @@
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.Property;
 import jdk.nashorn.internal.runtime.PropertyMap;
-import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
@@ -407,7 +406,7 @@
             try {
                 final Object toString = TO_STRING.getGetter().invokeExact(sobj);
 
-                if (toString instanceof ScriptFunction) {
+                if (Bootstrap.isCallable(toString)) {
                     return TO_STRING.getInvoker().invokeExact(toString, sobj);
                 }
             } catch (final RuntimeException | Error e) {
--- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java	Tue Aug 06 17:01:05 2013 -0700
@@ -75,7 +75,7 @@
      *
      * @param map property map
      */
-    public PrototypeObject(final PropertyMap map) {
+    PrototypeObject(final PropertyMap map) {
         this(Global.instance(), map);
     }
 
@@ -89,7 +89,7 @@
      * @param self self reference
      * @return constructor, probably, but not necessarily, a {@link ScriptFunction}
      */
-    public static Object getConstructor(final Object self) {
+    static Object getConstructor(final Object self) {
         return (self instanceof PrototypeObject) ?
             ((PrototypeObject)self).getConstructor() :
             UNDEFINED;
@@ -100,7 +100,7 @@
      * @param self self reference
      * @param constructor constructor, probably, but not necessarily, a {@link ScriptFunction}
      */
-    public static void setConstructor(final Object self, final Object constructor) {
+    static void setConstructor(final Object self, final Object constructor) {
         if (self instanceof PrototypeObject) {
             ((PrototypeObject)self).setConstructor(constructor);
         }
--- a/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java	Tue Aug 06 17:01:05 2013 -0700
@@ -25,6 +25,7 @@
 
 package jdk.nashorn.internal.parser;
 
+import static jdk.nashorn.internal.parser.TokenType.COMMENT;
 import static jdk.nashorn.internal.parser.TokenType.EOF;
 import static jdk.nashorn.internal.parser.TokenType.EOL;
 import static jdk.nashorn.internal.parser.TokenType.IDENT;
@@ -135,14 +136,27 @@
     }
 
     /**
-     * Seek next token that is not an EOL.
+     * Seek next token that is not an EOL or comment.
      *
      * @return tokenType of next token.
      */
     protected final TokenType next() {
         do {
             nextOrEOL();
-        } while (type == EOL);
+        } while (type == EOL || type == COMMENT);
+
+        return type;
+    }
+
+    /**
+     * Seek next token or EOL (skipping comments.)
+     *
+     * @return tokenType of next token.
+     */
+    protected final TokenType nextOrEOL() {
+        do {
+            nextToken();
+        } while (type == COMMENT);
 
         return type;
     }
@@ -152,7 +166,7 @@
      *
      * @return tokenType of next token.
      */
-    protected final TokenType nextOrEOL() {
+    private final TokenType nextToken() {
         // Capture last token tokenType.
         last = type;
         if (type != EOF) {
--- a/nashorn/src/jdk/nashorn/internal/parser/Lexer.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/parser/Lexer.java	Tue Aug 06 17:01:05 2013 -0700
@@ -26,6 +26,7 @@
 package jdk.nashorn.internal.parser;
 
 import static jdk.nashorn.internal.parser.TokenType.ADD;
+import static jdk.nashorn.internal.parser.TokenType.COMMENT;
 import static jdk.nashorn.internal.parser.TokenType.DECIMAL;
 import static jdk.nashorn.internal.parser.TokenType.EOF;
 import static jdk.nashorn.internal.parser.TokenType.EOL;
@@ -83,12 +84,70 @@
     /** Type of last token added. */
     private TokenType last;
 
-    private static final String JAVASCRIPT_WHITESPACE;
-    private static final String JAVASCRIPT_WHITESPACE_EOL;
-    private static final String JAVASCRIPT_WHITESPACE_IN_REGEXP;
+    private static final String SPACETAB = " \t";  // ASCII space and tab
+    private static final String LFCR     = "\n\r"; // line feed and carriage return (ctrl-m)
 
-    private static final String JSON_WHITESPACE;
-    private static final String JSON_WHITESPACE_EOL;
+    private static final String JSON_WHITESPACE_EOL = LFCR;
+    private static final String JSON_WHITESPACE     = SPACETAB + LFCR;
+
+    private static final String JAVASCRIPT_WHITESPACE_EOL =
+        LFCR +
+        "\u2028" + // line separator
+        "\u2029"   // paragraph separator
+        ;
+    private static final String JAVASCRIPT_WHITESPACE =
+        SPACETAB +
+        JAVASCRIPT_WHITESPACE_EOL +
+        "\u000b" + // tabulation line
+        "\u000c" + // ff (ctrl-l)
+        "\u00a0" + // Latin-1 space
+        "\u1680" + // Ogham space mark
+        "\u180e" + // separator, Mongolian vowel
+        "\u2000" + // en quad
+        "\u2001" + // em quad
+        "\u2002" + // en space
+        "\u2003" + // em space
+        "\u2004" + // three-per-em space
+        "\u2005" + // four-per-em space
+        "\u2006" + // six-per-em space
+        "\u2007" + // figure space
+        "\u2008" + // punctuation space
+        "\u2009" + // thin space
+        "\u200a" + // hair space
+        "\u202f" + // narrow no-break space
+        "\u205f" + // medium mathematical space
+        "\u3000" + // ideographic space
+        "\ufeff"   // byte order mark
+        ;
+
+    private static final String JAVASCRIPT_WHITESPACE_IN_REGEXP =
+        "\\u000a" + // line feed
+        "\\u000d" + // carriage return (ctrl-m)
+        "\\u2028" + // line separator
+        "\\u2029" + // paragraph separator
+        "\\u0009" + // tab
+        "\\u0020" + // ASCII space
+        "\\u000b" + // tabulation line
+        "\\u000c" + // ff (ctrl-l)
+        "\\u00a0" + // Latin-1 space
+        "\\u1680" + // Ogham space mark
+        "\\u180e" + // separator, Mongolian vowel
+        "\\u2000" + // en quad
+        "\\u2001" + // em quad
+        "\\u2002" + // en space
+        "\\u2003" + // em space
+        "\\u2004" + // three-per-em space
+        "\\u2005" + // four-per-em space
+        "\\u2006" + // six-per-em space
+        "\\u2007" + // figure space
+        "\\u2008" + // punctuation space
+        "\\u2009" + // thin space
+        "\\u200a" + // hair space
+        "\\u202f" + // narrow no-break space
+        "\\u205f" + // medium mathematical space
+        "\\u3000" + // ideographic space
+        "\\ufeff"   // byte order mark
+        ;
 
     static String unicodeEscape(final char ch) {
         final StringBuilder sb = new StringBuilder();
@@ -104,65 +163,6 @@
         return sb.toString();
     }
 
-    static {
-        final StringBuilder ws       = new StringBuilder();
-        final StringBuilder wsEOL    = new StringBuilder();
-        final StringBuilder wsRegExp = new StringBuilder();
-        final StringBuilder jsonWs   = new StringBuilder();
-
-        jsonWs.append((char)0x000a);
-        jsonWs.append((char)0x000d);
-        JSON_WHITESPACE_EOL = jsonWs.toString();
-
-        jsonWs.append((char)0x0009);
-        jsonWs.append((char)0x0020);
-        JSON_WHITESPACE = jsonWs.toString();
-
-        for (int i = 0; i <= 0xffff; i++) {
-           switch (i) {
-            case 0x000a: // line feed
-            case 0x000d: // carriage return (ctrl-m)
-            case 0x2028: // line separator
-            case 0x2029: // paragraph separator
-                wsEOL.append((char)i);
-            case 0x0009: // tab
-            case 0x0020: // ASCII space
-            case 0x000b: // tabulation line
-            case 0x000c: // ff (ctrl-l)
-            case 0x00a0: // Latin-1 space
-            case 0x1680: // Ogham space mark
-            case 0x180e: // separator, Mongolian vowel
-            case 0x2000: // en quad
-            case 0x2001: // em quad
-            case 0x2002: // en space
-            case 0x2003: // em space
-            case 0x2004: // three-per-em space
-            case 0x2005: // four-per-em space
-            case 0x2006: // six-per-em space
-            case 0x2007: // figure space
-            case 0x2008: // punctuation space
-            case 0x2009: // thin space
-            case 0x200a: // hair space
-            case 0x202f: // narrow no-break space
-            case 0x205f: // medium mathematical space
-            case 0x3000: // ideographic space
-            case 0xfeff: // byte order mark
-                ws.append((char)i);
-
-                wsRegExp.append(Lexer.unicodeEscape((char)i));
-                break;
-
-            default:
-                break;
-            }
-        }
-
-        JAVASCRIPT_WHITESPACE = ws.toString();
-        JAVASCRIPT_WHITESPACE_EOL = wsEOL.toString();
-        JAVASCRIPT_WHITESPACE_IN_REGEXP = wsRegExp.toString();
-
-    }
-
     /**
      * Constructor
      *
@@ -427,6 +427,9 @@
      * @return True if a comment.
      */
     protected boolean skipComments() {
+        // Save the current position.
+        final int start = position;
+
         if (ch0 == '/') {
             // Is it a // comment.
             if (ch1 == '/') {
@@ -437,10 +440,9 @@
                     skip(1);
                 }
                 // Did detect a comment.
+                add(COMMENT, start);
                 return true;
             } else if (ch1 == '*') {
-                // Record beginning of comment.
-                final int start = position;
                 // Skip over /*.
                 skip(2);
                 // Scan for */.
@@ -462,11 +464,11 @@
                 }
 
                 // Did detect a comment.
+                add(COMMENT, start);
                 return true;
             }
-        }
-
-        if (scripting && ch0 == '#') {
+        } else if (ch0 == '#') {
+            assert scripting;
             // shell style comment
             // Skip over #.
             skip(1);
@@ -475,6 +477,7 @@
                 skip(1);
             }
             // Did detect a comment.
+            add(COMMENT, start);
             return true;
         }
 
@@ -563,7 +566,7 @@
      *
      * @param token the token.
      * @param startTokenType the token type.
-     * @parasm lir LineInfoReceiver that receives line info for multi-line string literals.
+     * @param lir LineInfoReceiver that receives line info for multi-line string literals.
      * @return True if a literal beginning with startToken was found and scanned.
      */
     protected boolean scanLiteral(final long token, final TokenType startTokenType, final LineInfoReceiver lir) {
@@ -1461,11 +1464,10 @@
             final State restState = saveState();
             // keep line number updated
             int lastLine = line;
-            int lastLinePosition = linePosition;
 
             skipLine(false);
             lastLine++;
-            lastLinePosition = position;
+            int lastLinePosition = position;
             restState.setLimit(position);
 
             // Record beginning of string.
--- a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java	Tue Aug 06 17:01:05 2013 -0700
@@ -44,6 +44,7 @@
     ERROR          (SPECIAL,  null),
     EOF            (SPECIAL,  null),
     EOL            (SPECIAL,  null),
+    COMMENT        (SPECIAL,  null),
 
     NOT            (UNARY,   "!",    14, false),
     NE             (BINARY,  "!=",    9, true),
--- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java	Tue Aug 06 17:01:05 2013 -0700
@@ -51,7 +51,7 @@
  * An AccessorProperty is the most generic property type. An AccessorProperty is
  * represented as fields in a ScriptObject class.
  */
-public class AccessorProperty extends Property {
+public final class AccessorProperty extends Property {
     private static final MethodHandles.Lookup lookup = MethodHandles.lookup();
     private static final MethodHandle REPLACE_MAP = findOwnMH("replaceMap", Object.class, Object.class, PropertyMap.class, String.class, Class.class, Class.class);
 
@@ -149,7 +149,7 @@
      * @param property  accessor property to rebind
      * @param delegate  delegate object to rebind receiver to
      */
-    public AccessorProperty(final AccessorProperty property, final Object delegate) {
+    AccessorProperty(final AccessorProperty property, final Object delegate) {
         super(property);
 
         this.primitiveGetter = bindTo(property.primitiveGetter, delegate);
@@ -185,7 +185,7 @@
      * @param getter the property getter
      * @param setter the property setter or null if non writable, non configurable
      */
-    public AccessorProperty(final String key, final int flags, final int slot, final MethodHandle getter, final MethodHandle setter) {
+    AccessorProperty(final String key, final int flags, final int slot, final MethodHandle getter, final MethodHandle setter) {
         super(key, flags, slot);
 
         // we don't need to prep the setters these will never be invalidated as this is a nasgen
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java	Tue Aug 06 17:01:05 2013 -0700
@@ -36,13 +36,17 @@
 import java.io.PrintWriter;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.reflect.Modifier;
 import java.util.concurrent.atomic.AtomicLong;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.CodeSigner;
 import java.security.CodeSource;
+import java.security.Permissions;
 import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
 import java.util.Map;
 import jdk.internal.org.objectweb.asm.ClassReader;
 import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
@@ -121,11 +125,6 @@
      * @param global the global scope
      */
     public static void setGlobal(final ScriptObject global) {
-        final SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            sm.checkPermission(new RuntimePermission("nashorn.setGlobal"));
-        }
-
         if (global != null && !(global instanceof Global)) {
             throw new IllegalArgumentException("global is not an instance of Global!");
         }
@@ -205,6 +204,7 @@
 
     private static final ClassLoader myLoader = Context.class.getClassLoader();
     private static final StructureLoader sharedLoader;
+    private static final AccessControlContext NO_PERMISSIONS_CONTEXT;
 
     static {
         sharedLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
@@ -213,6 +213,7 @@
                 return new StructureLoader(myLoader, null);
             }
         });
+        NO_PERMISSIONS_CONTEXT = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) });
     }
 
     /**
@@ -483,7 +484,7 @@
                 source = new Source(name, script);
             }
         } else if (src instanceof Map) {
-            final Map map = (Map)src;
+            final Map<?,?> map = (Map<?,?>)src;
             if (map.containsKey("script") && map.containsKey("name")) {
                 final String script = JSType.toString(map.get("script"));
                 final String name   = JSType.toString(map.get("name"));
@@ -553,25 +554,60 @@
      * @throws ClassNotFoundException if structure class cannot be resolved
      */
     public static Class<?> forStructureClass(final String fullName) throws ClassNotFoundException {
+        if (System.getSecurityManager() != null && !NashornLoader.isStructureClass(fullName)) {
+            throw new ClassNotFoundException(fullName);
+        }
         return Class.forName(fullName, true, sharedLoader);
     }
 
     /**
-     * Checks that the given package can be accessed from current call stack.
+     * Checks that the given package can be accessed from no permissions context.
      *
      * @param fullName fully qualified package name
+     * @throw SecurityException if not accessible
      */
     public static void checkPackageAccess(final String fullName) {
         final int index = fullName.lastIndexOf('.');
         if (index != -1) {
             final SecurityManager sm = System.getSecurityManager();
             if (sm != null) {
-                sm.checkPackageAccess(fullName.substring(0, index));
+                AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                    @Override
+                    public Void run() {
+                        sm.checkPackageAccess(fullName.substring(0, index));
+                        return null;
+                    }
+                }, NO_PERMISSIONS_CONTEXT);
             }
         }
     }
 
     /**
+     * Checks that the given package can be accessed from no permissions context.
+     *
+     * @param fullName fully qualified package name
+     * @return true if package is accessible, false otherwise
+     */
+    public static boolean isAccessiblePackage(final String fullName) {
+        try {
+            checkPackageAccess(fullName);
+            return true;
+        } catch (final SecurityException se) {
+            return false;
+        }
+    }
+
+    /**
+     * Checks that the given Class is public and it can be accessed from no permissions context.
+     *
+     * @param clazz Class object to check
+     * @return true if Class is accessible, false otherwise
+     */
+    public static boolean isAccessibleClass(final Class<?> clazz) {
+        return Modifier.isPublic(clazz.getModifiers()) && Context.isAccessiblePackage(clazz.getName());
+    }
+
+    /**
      * Lookup a Java class. This is used for JSR-223 stuff linking in from
      * {@code jdk.nashorn.internal.objects.NativeJava} and {@code jdk.nashorn.internal.runtime.NativeJavaPackage}
      *
@@ -626,7 +662,7 @@
             // No verification when security manager is around as verifier
             // may load further classes - which should be avoided.
             if (System.getSecurityManager() == null) {
-                CheckClassAdapter.verify(new ClassReader(bytecode), scriptLoader, false, new PrintWriter(System.err, true));
+                CheckClassAdapter.verify(new ClassReader(bytecode), sharedLoader, false, new PrintWriter(System.err, true));
             }
         }
     }
@@ -645,12 +681,7 @@
      * @return the global script object
      */
     public ScriptObject newGlobal() {
-        final SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            sm.checkPermission(new RuntimePermission("nashorn.newGlobal"));
-        }
-
-        return newGlobalTrusted();
+        return new Global(this);
     }
 
     /**
@@ -828,10 +859,6 @@
              });
     }
 
-    private ScriptObject newGlobalTrusted() {
-        return new Global(this);
-    }
-
     private long getUniqueScriptId() {
         return uniqueScriptId.getAndIncrement();
     }
--- a/nashorn/src/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java	Tue Aug 06 17:01:05 2013 -0700
@@ -33,7 +33,7 @@
  * This is a subclass that represents a script function that may not be regenerated.
  * This is used for example for bound functions and builtins.
  */
-public final class FinalScriptFunctionData extends ScriptFunctionData {
+final class FinalScriptFunctionData extends ScriptFunctionData {
 
     /**
      * Constructor - used for bind
--- a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java	Tue Aug 06 17:01:05 2013 -0700
@@ -31,6 +31,7 @@
 import java.util.ListIterator;
 import java.util.NoSuchElementException;
 import java.util.RandomAccess;
+import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.InvokeByName;
 
 /**
@@ -46,7 +47,7 @@
  * operations respectively, while {@link #addLast(Object)} and {@link #removeLast()} will translate to {@code push} and
  * {@code pop}.
  */
-public class ListAdapter extends AbstractList<Object> implements RandomAccess, Deque<Object> {
+public final class ListAdapter extends AbstractList<Object> implements RandomAccess, Deque<Object> {
     // These add to the back and front of the list
     private static final InvokeByName PUSH    = new InvokeByName("push",    ScriptObject.class, void.class, Object.class);
     private static final InvokeByName UNSHIFT = new InvokeByName("unshift", ScriptObject.class, void.class, Object.class);
@@ -157,7 +158,7 @@
         }
     }
     private static void checkFunction(Object fn, InvokeByName invoke) {
-        if(!(fn instanceof ScriptFunction)) {
+        if(!(Bootstrap.isCallable(fn))) {
             throw new UnsupportedOperationException("The script object doesn't have a function named " + invoke.getName());
         }
     }
--- a/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java	Tue Aug 06 17:01:05 2013 -0700
@@ -118,6 +118,10 @@
         return permCollection;
     }
 
+    static boolean isStructureClass(final String fullName) {
+        return fullName.startsWith(SCRIPTS_PKG);
+    }
+
     /**
      * Create a secure URL class loader for the given classpath
      * @param classPath classpath for the loader to search from
--- a/nashorn/src/jdk/nashorn/internal/runtime/NativeJavaPackage.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/NativeJavaPackage.java	Tue Aug 06 17:01:05 2013 -0700
@@ -84,8 +84,8 @@
      * @param proto proto
      */
     public NativeJavaPackage(final String name, final ScriptObject proto) {
+        super(proto, null);
         this.name = name;
-        this.setProto(proto);
     }
 
     @Override
--- a/nashorn/src/jdk/nashorn/internal/runtime/Property.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Property.java	Tue Aug 06 17:01:05 2013 -0700
@@ -100,7 +100,7 @@
      * @param flags property flags
      * @param slot  property field number or spill slot
      */
-    public Property(final String key, final int flags, final int slot) {
+    Property(final String key, final int flags, final int slot) {
         assert key != null;
         this.key   = key;
         this.flags = flags;
@@ -112,7 +112,7 @@
      *
      * @param property source property
      */
-    protected Property(final Property property) {
+    Property(final Property property) {
         this.key   = property.key;
         this.flags = property.flags;
         this.slot  = property.slot;
@@ -123,7 +123,7 @@
      *
      * @return cloned property
      */
-    protected abstract Property copy();
+    abstract Property copy();
 
     /**
      * Property flag utility method for {@link PropertyDescriptor}s. Given two property descriptors,
--- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java	Tue Aug 06 17:01:05 2013 -0700
@@ -32,6 +32,7 @@
  * Helper class to manage property listeners and notification.
  */
 public class PropertyListenerManager implements PropertyListener {
+    PropertyListenerManager() {}
 
     /** property listeners for this object. */
     private Map<PropertyListener,Boolean> listeners;
--- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java	Tue Aug 06 17:01:05 2013 -0700
@@ -352,11 +352,15 @@
         return newMap;
     }
 
-    /*
+    /**
      * Make a new UserAccessorProperty property. getter and setter functions are stored in
      * this ScriptObject and slot values are used in property object. Note that slots
      * are assigned speculatively and should be added to map before adding other
      * properties.
+     *
+     * @param key the property name
+     * @param propertyFlags attribute flags of the property
+     * @return the newly created UserAccessorProperty
      */
     public UserAccessorProperty newUserAccessors(final String key, final int propertyFlags) {
         int oldSpillLength = spillLength;
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunctionData.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunctionData.java	Tue Aug 06 17:01:05 2013 -0700
@@ -67,7 +67,7 @@
      * @param isBuiltin     is the function built in
      * @param isConstructor is the function a constructor
      */
-    protected ScriptFunctionData(final String name, final int arity, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
+    ScriptFunctionData(final String name, final int arity, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
         this.name          = name;
         this.arity         = arity;
         this.code          = new CompiledFunctions();
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Tue Aug 06 17:01:05 2013 -0700
@@ -1046,6 +1046,15 @@
     }
 
     /**
+     * Checks if this object belongs to the given context
+     * @param ctx context to check against
+     * @return true if this object belongs to the given context
+     */
+    public final boolean isOfContext(final Context ctx) {
+        return context == ctx;
+    }
+
+    /**
      * Return the current context from the object's map.
      * @return Current context.
      */
@@ -3192,9 +3201,15 @@
         return true;
     }
 
-    /*
+    /**
      * Make a new UserAccessorProperty property. getter and setter functions are stored in
      * this ScriptObject and slot values are used in property object.
+     *
+     * @param key the property name
+     * @param propertyFlags attribute flags of the property
+     * @param getter getter function for the property
+     * @param setter setter function for the property
+     * @return the newly created UserAccessorProperty
      */
     protected final UserAccessorProperty newUserAccessors(final String key, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) {
         final UserAccessorProperty property = getMap().newUserAccessors(key, propertyFlags);
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java	Tue Aug 06 17:01:05 2013 -0700
@@ -335,9 +335,7 @@
      */
     public static Object checkAndApply(final ScriptFunction target, final Object self, final Object... args) {
         final ScriptObject global = Context.getGlobalTrusted();
-        if (! (global instanceof GlobalObject)) {
-            throw new IllegalStateException("No current global set");
-        }
+        assert (global instanceof GlobalObject): "No current global set";
 
         if (target.getContext() != global.getContext()) {
             throw new IllegalArgumentException("'target' function is not from current Context");
@@ -383,9 +381,7 @@
      */
     public static Object checkAndConstruct(final ScriptFunction target, final Object... args) {
         final ScriptObject global = Context.getGlobalTrusted();
-        if (! (global instanceof GlobalObject)) {
-            throw new IllegalStateException("No current global set");
-        }
+        assert (global instanceof GlobalObject): "No current global set";
 
         if (target.getContext() != global.getContext()) {
             throw new IllegalArgumentException("'target' function is not from current Context");
@@ -395,7 +391,7 @@
         return construct(target, args);
     }
 
-    /*
+    /**
      * Call a script function as a constructor with given args.
      *
      * @param target ScriptFunction object.
--- a/nashorn/src/jdk/nashorn/internal/runtime/Source.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Source.java	Tue Aug 06 17:01:05 2013 -0700
@@ -384,11 +384,7 @@
         }
 
         final byte[] buf = Files.readAllBytes(file.toPath());
-        if (cs != null) {
-            return new String(buf, cs).toCharArray();
-        } else {
-            return byteToCharArray(buf);
-        }
+        return (cs != null)? new String(buf, cs).toCharArray() : byteToCharArray(buf);
     }
 
     /**
@@ -465,11 +461,7 @@
     }
 
     private static char[] readFully(final InputStream is, final Charset cs) throws IOException {
-        if (cs != null) {
-            return new String(readBytes(is), cs).toCharArray();
-        } else {
-            return readFully(is);
-        }
+        return (cs != null)? new String(readBytes(is), cs).toCharArray() : readFully(is);
     }
 
     private static char[] readFully(final InputStream is) throws IOException {
--- a/nashorn/src/jdk/nashorn/internal/runtime/UserAccessorProperty.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/UserAccessorProperty.java	Tue Aug 06 17:01:05 2013 -0700
@@ -83,7 +83,7 @@
      * @param getterSlot getter slot, starting at first embed
      * @param setterSlot setter slot, starting at first embed
      */
-    public UserAccessorProperty(final String key, final int flags, final int getterSlot, final int setterSlot) {
+    UserAccessorProperty(final String key, final int flags, final int getterSlot, final int setterSlot) {
         super(key, flags, -1);
         this.getterSlot = getterSlot;
         this.setterSlot = setterSlot;
--- a/nashorn/src/jdk/nashorn/internal/runtime/WithObject.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/WithObject.java	Tue Aug 06 17:01:05 2013 -0700
@@ -57,11 +57,9 @@
      * @param scope scope object
      * @param expression with expression
      */
-    public WithObject(final ScriptObject scope, final Object expression) {
-        super();
-
+    WithObject(final ScriptObject scope, final Object expression) {
+        super(scope, null);
         setIsScope();
-        setProto(scope);
         this.expression = expression;
     }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/IteratorAction.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/IteratorAction.java	Tue Aug 06 17:01:05 2013 -0700
@@ -31,6 +31,7 @@
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
+import jdk.nashorn.internal.runtime.linker.Bootstrap;
 
 /**
  * Helper class for the various map/apply functions in {@link jdk.nashorn.internal.objects.NativeArray}.
@@ -103,6 +104,8 @@
         } else if (callbackfn instanceof ScriptObjectMirror &&
             ((ScriptObjectMirror)callbackfn).isFunction()) {
             strict = ((ScriptObjectMirror)callbackfn).isStrictFunction();
+        } else if (Bootstrap.isDynamicMethod(callbackfn) || Bootstrap.isFunctionalInterfaceObject(callbackfn)) {
+            strict = false;
         } else {
             throw typeError("not.a.function", ScriptRuntime.safeToString(callbackfn));
         }
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/AdaptationException.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/AdaptationException.java	Tue Aug 06 17:01:05 2013 -0700
@@ -26,7 +26,7 @@
 package jdk.nashorn.internal.runtime.linker;
 
 @SuppressWarnings("serial")
-class AdaptationException extends Exception {
+final class AdaptationException extends Exception {
     private final AdaptationResult adaptationResult;
 
     AdaptationException(final AdaptationResult.Outcome outcome, final String classList) {
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/AdaptationResult.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/AdaptationResult.java	Tue Aug 06 17:01:05 2013 -0700
@@ -32,7 +32,7 @@
  * A result of generating an adapter for a class. A tuple of an outcome and - in case of an error outcome - a list of
  * classes that caused the error.
  */
-class AdaptationResult {
+final class AdaptationResult {
     /**
      * Contains various outcomes for attempting to generate an adapter class. These are stored in AdapterInfo instances.
      * We have a successful outcome (adapter class was generated) and four possible error outcomes: superclass is final,
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java	Tue Aug 06 17:01:05 2013 -0700
@@ -38,8 +38,12 @@
 import jdk.internal.dynalink.beans.BeansLinker;
 import jdk.internal.dynalink.linker.GuardedInvocation;
 import jdk.internal.dynalink.linker.LinkerServices;
+import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
 import jdk.nashorn.internal.codegen.RuntimeCallSite;
+import jdk.nashorn.internal.runtime.JSType;
+import jdk.nashorn.internal.runtime.ScriptFunction;
+import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.options.Options;
 
 /**
@@ -68,6 +72,41 @@
     }
 
     /**
+     * Returns if the given object is a "callable"
+     * @param obj object to be checked for callability
+     * @return true if the obj is callable
+     */
+    public static boolean isCallable(final Object obj) {
+        if (obj == ScriptRuntime.UNDEFINED || obj == null) {
+            return false;
+        }
+
+        return obj instanceof ScriptFunction ||
+            ((obj instanceof ScriptObjectMirror) && ((ScriptObjectMirror)obj).isFunction()) ||
+            isDynamicMethod(obj) ||
+            isFunctionalInterfaceObject(obj);
+    }
+
+    /**
+     * Returns if the given object is a dynalink Dynamic method
+     * @param obj object to be checked
+     * @return true if the obj is a dynamic method
+     */
+    public static boolean isDynamicMethod(final Object obj) {
+        return obj instanceof BoundDynamicMethod || BeansLinker.isDynamicMethod(obj);
+    }
+
+    /**
+     * Returns if the given object is an instance of an interface annotated with
+     * java.lang.FunctionalInterface
+     * @param obj object to be checked
+     * @return true if the obj is an instance of @FunctionalInterface interface
+     */
+    public static boolean isFunctionalInterfaceObject(final Object obj) {
+        return !JSType.isPrimitive(obj) && (NashornBottomLinker.getFunctionalInterfaceMethod(obj.getClass()) != null);
+    }
+
+    /**
      * Create a call site and link it for Nashorn. This version of the method conforms to the invokedynamic bootstrap
      * method expected signature and is referenced from Nashorn generated bytecode as the bootstrap method for all
      * invokedynamic instructions.
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/InvokeByName.java	Tue Aug 06 17:01:05 2013 -0700
@@ -58,7 +58,7 @@
  * you dynamically invoke a function with the same name from multiple places in your code, it is advisable to create a
  * separate instance of this class for every place.
  */
-public class InvokeByName {
+public final class InvokeByName {
     private final String name;
     private final MethodHandle getter;
     private final MethodHandle invoker;
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java	Tue Aug 06 17:01:05 2013 -0700
@@ -45,18 +45,17 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodType;
+import java.lang.reflect.AccessibleObject;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-import java.security.SecureRandom;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Random;
 import java.util.Set;
 import jdk.internal.org.objectweb.asm.ClassWriter;
 import jdk.internal.org.objectweb.asm.Label;
@@ -66,6 +65,7 @@
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
+import sun.reflect.CallerSensitive;
 
 /**
  * Generates bytecode for a Java adapter class. Used by the {@link JavaAdapterFactory}.
@@ -121,7 +121,23 @@
  * constructor's trailing position and thus provide further instance-specific overrides. The order of invocation is
  * always instance-specified method, then a class-specified method, and finally the superclass method.
  */
-final class JavaAdapterBytecodeGenerator extends JavaAdapterGeneratorBase {
+final class JavaAdapterBytecodeGenerator {
+    static final Type CONTEXT_TYPE       = Type.getType(Context.class);
+    static final Type OBJECT_TYPE        = Type.getType(Object.class);
+    static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class);
+
+    static final String CONTEXT_TYPE_NAME = CONTEXT_TYPE.getInternalName();
+    static final String OBJECT_TYPE_NAME  = OBJECT_TYPE.getInternalName();
+
+    static final String INIT = "<init>";
+
+    static final String GLOBAL_FIELD_NAME = "global";
+
+    static final String SCRIPT_OBJECT_TYPE_DESCRIPTOR = SCRIPT_OBJECT_TYPE.getDescriptor();
+
+    static final String SET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, SCRIPT_OBJECT_TYPE);
+    static final String VOID_NOARG_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE);
+
     private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class);
     private static final Type STRING_TYPE = Type.getType(String.class);
     private static final Type METHOD_TYPE_TYPE = Type.getType(MethodType.class);
@@ -147,11 +163,11 @@
 
     // Package used when the adapter can't be defined in the adaptee's package (either because it's sealed, or because
     // it's a java.* package.
-    private static final String ADAPTER_PACKAGE_PREFIX = "jdk/nashorn/internal/javaadapters/";
+    private static final String ADAPTER_PACKAGE_PREFIX = "jdk/nashorn/javaadapters/";
     // Class name suffix used to append to the adaptee class name, when it can be defined in the adaptee's package.
     private static final String ADAPTER_CLASS_NAME_SUFFIX = "$$NashornJavaAdapter";
     private static final String JAVA_PACKAGE_PREFIX = "java/";
-    private static final int MAX_GENERATED_TYPE_NAME_LENGTH = 238; //255 - 17; 17 is the maximum possible length for the global setter inner class suffix
+    private static final int MAX_GENERATED_TYPE_NAME_LENGTH = 255;
 
     private static final String CLASS_INIT = "<clinit>";
     private static final String STATIC_GLOBAL_FIELD_NAME = "staticGlobal";
@@ -161,8 +177,6 @@
      */
     private static final Collection<MethodInfo> EXCLUDED = getExcludedMethods();
 
-    private static final Random random = new SecureRandom();
-
     // This is the superclass for our generated adapter.
     private final Class<?> superClass;
     // Class loader used as the parent for the class loader we'll create to load the generated class. It will be a class
@@ -175,8 +189,6 @@
     private final String superClassName;
     // Binary name of the generated class.
     private final String generatedClassName;
-    // Binary name of the PrivilegedAction inner class that is used to
-    private final String globalSetterClassName;
     private final Set<String> usedFieldNames = new HashSet<>();
     private final Set<String> abstractMethodNames = new HashSet<>();
     private final String samName;
@@ -214,15 +226,6 @@
         superClassName = Type.getInternalName(superClass);
         generatedClassName = getGeneratedClassName(superClass, interfaces);
 
-        // Randomize the name of the privileged global setter, to make it non-feasible to find.
-        final long l;
-        synchronized(random) {
-            l = random.nextLong();
-        }
-
-        // NOTE: they way this class name is calculated affects the value of MAX_GENERATED_TYPE_NAME_LENGTH constant. If
-        // you change the calculation of globalSetterClassName, adjust the constant too.
-        globalSetterClassName = generatedClassName.concat("$" + Long.toHexString(l & Long.MAX_VALUE));
         cw.visit(Opcodes.V1_7, ACC_PUBLIC | ACC_SUPER | ACC_FINAL, generatedClassName, null, superClassName, getInternalTypeNames(interfaces));
 
         generateGlobalFields();
@@ -250,7 +253,7 @@
     }
 
     JavaAdapterClassLoader createAdapterClassLoader() {
-        return new JavaAdapterClassLoader(generatedClassName, cw.toByteArray(), globalSetterClassName);
+        return new JavaAdapterClassLoader(generatedClassName, cw.toByteArray());
     }
 
     boolean isAutoConvertibleFromFunction() {
@@ -367,7 +370,7 @@
         boolean gotCtor = false;
         for (final Constructor<?> ctor: superClass.getDeclaredConstructors()) {
             final int modifier = ctor.getModifiers();
-            if((modifier & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
+            if((modifier & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0 && !isCallerSensitive(ctor)) {
                 generateConstructors(ctor);
                 gotCtor = true;
             }
@@ -511,8 +514,8 @@
         mv.invokestatic(CONTEXT_TYPE_NAME, "getGlobal", GET_GLOBAL_METHOD_DESCRIPTOR);
     }
 
-    private void invokeSetGlobal(final InstructionAdapter mv) {
-        mv.invokestatic(globalSetterClassName, "setGlobal", SET_GLOBAL_METHOD_DESCRIPTOR);
+    private static void invokeSetGlobal(final InstructionAdapter mv) {
+        mv.invokestatic(CONTEXT_TYPE_NAME, "setGlobal", SET_GLOBAL_METHOD_DESCRIPTOR);
     }
 
     /**
@@ -794,7 +797,7 @@
      * entry.
      * @param globalsDifferVar index of the boolean local variable that is true if the global needs to be restored.
      */
-    private void emitFinally(final InstructionAdapter mv, final int currentGlobalVar, final int globalsDifferVar) {
+    private static void emitFinally(final InstructionAdapter mv, final int currentGlobalVar, final int globalsDifferVar) {
         // Emit code to restore the previous Nashorn global if needed
         mv.visitVarInsn(ILOAD, globalsDifferVar);
         final Label skip = new Label();
@@ -832,7 +835,7 @@
                 }
                 if (Modifier.isPublic(m) || Modifier.isProtected(m)) {
                     final MethodInfo mi = new MethodInfo(typeMethod);
-                    if (Modifier.isFinal(m)) {
+                    if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) {
                         finalMethods.add(mi);
                     } else if (!finalMethods.contains(mi) && methodInfos.add(mi)) {
                         if (Modifier.isAbstract(m)) {
@@ -909,4 +912,8 @@
         final Class<?> superClass = c1.getSuperclass();
         return superClass.isAssignableFrom(c2) ? superClass : assignableSuperClass(superClass, c2);
     }
+
+    private static boolean isCallerSensitive(final AccessibleObject e) {
+        return e.isAnnotationPresent(CallerSensitive.class);
+    }
 }
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java	Fri Jun 28 16:26:54 2013 -0400
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterClassLoader.java	Tue Aug 06 17:01:05 2013 -0700
@@ -25,16 +25,6 @@
 
 package jdk.nashorn.internal.runtime.linker;
 
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE;
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;
-import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
-import static jdk.internal.org.objectweb.asm.Opcodes.ACONST_NULL;
-import static jdk.internal.org.objectweb.asm.Opcodes.ALOAD;
-import static jdk.internal.org.objectweb.asm.Opcodes.ARETURN;
-import static jdk.internal.org.objectweb.asm.Opcodes.RETURN;
-
 import java.security.AccessController;
 import java.security.AllPermission;
 import java.security.CodeSigner;
@@ -45,12 +35,6 @@
 import java.security.SecureClassLoader;
 
 import jdk.internal.dynalink.beans.StaticClass;
-import jdk.internal.org.objectweb.asm.ClassWriter;
-import jdk.internal.org.objectweb.asm.Opcodes;
-import jdk.internal.org.objectweb.asm.Type;
-import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
-import jdk.nashorn.internal.runtime.Context;
-import jdk.nashorn.internal.runtime.ScriptObject;
 
 /**
  * This class encapsulates the bytecode of the adapter class and can be used to load it into the JVM as an actual Class.
@@ -60,22 +44,15 @@
  * class are normally created by {@link JavaAdapterBytecodeGenerator}.
  */
 @SuppressWarnings("javadoc")
-class JavaAdapterClassLoader extends JavaAdapterGeneratorBase {
-    private static final Type PRIVILEGED_ACTION_TYPE = Type.getType(PrivilegedAction.class);
-
-    private static final String PRIVILEGED_ACTION_TYPE_NAME = PRIVILEGED_ACTION_TYPE.getInternalName();
-    private static final String PRIVILEGED_RUN_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE);
-
+final class JavaAdapterClassLoader {
     private static final ProtectionDomain GENERATED_PROTECTION_DOMAIN = createGeneratedProtectionDomain();
 
     private final String className;
     private final byte[] classBytes;
-    private final String globalSetterClassName;
 
-    JavaAdapterClassLoader(String className, byte[] classBytes, String globalSetterClassName) {
+    JavaAdapterClassLoader(String className, byte[] classBytes) {
         this.className = className.replace('/', '.');
         this.classBytes = classBytes;
-        this.globalSetterClassName = globalSetterClassName.replace('/', '.');
     }
 
     /**
@@ -96,16 +73,6 @@
         });
     }
 
-    private static class AdapterLoader extends SecureClassLoader {
-        AdapterLoader(ClassLoader parent) {
-            super(parent);
-        }
-    }
-
-    static boolean isAdapterClass(Class<?> clazz) {
-        return clazz.getClassLoader() instanceof AdapterLoader;
-    }
-
     // Note that the adapter class is created in the protection domain of the class/interface being
     // extended/implemented, and only the privileged global setter action class is generated in the protection domain
     // of Nashorn itself. Also note that the creation and loading of the global setter is deferred until it is
@@ -114,9 +81,8 @@
     // with ability to introspect on the class and use setAccessible(true) on it could invoke the method. It's a
     // security tradeoff...
     private ClassLoader createClassLoader(final ClassLoader parentLoader) {
-        return new AdapterLoader(parentLoader) {
+        return new SecureClassLoader(parentLoader) {
             private final ClassLoader myLoader = getClass().getClassLoader();
-            private final ProtectionDomain myProtectionDomain = getClass().getProtectionDomain();