Merge latest green inbound changeset and mozilla-central
authorEd Morley <emorley@mozilla.com>
Fri, 10 May 2013 09:13:03 +0100
changeset 142426 08be63954b6bce6e8aaa505352e11c4541d365c1
parent 142425 7f4e7df5a393ec1cee7280ac66b3b30273f284ed (current diff)
parent 142326 e44c0b1eb2e3da774b4f7dc85667d71201276e80 (diff)
child 142427 2673016e7df4dc1fbad0b6ec93d8bdee917a888b
child 142449 08561a44b09b6abe895c541bbc3b0d6bce7158ef
child 142535 bc406ec71d6dceca8840806c3ce9174814e59ab4
push id2579
push userakeybl@mozilla.com
push dateMon, 24 Jun 2013 18:52:47 +0000
treeherdermozilla-beta@b69b7de8a05a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone23.0a1
first release with
nightly linux32
08be63954b6b / 23.0a1 / 20130510041606 / files
nightly linux64
08be63954b6b / 23.0a1 / 20130510041606 / files
nightly mac
08be63954b6b / 23.0a1 / 20130510041606 / files
nightly win32
08be63954b6b / 23.0a1 / 20130510041606 / files
nightly win64
08be63954b6b / 23.0a1 / 20130510041606 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge latest green inbound changeset and mozilla-central
content/html/content/reftests/hidden-1-ref.html
content/html/content/reftests/hidden-1a.html
content/html/content/reftests/hidden-1b.html
content/html/content/reftests/hidden-1c.html
content/html/content/reftests/hidden-1d.html
content/html/content/reftests/hidden-1e.html
content/html/content/reftests/hidden-1f.html
content/html/content/reftests/hidden-1g.html
content/html/content/reftests/hidden-2-ref.svg
content/html/content/reftests/hidden-2.svg
dom/imptests/failures/html/html/dom/documents/dta/Makefile.in
dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/Makefile.in
dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/moz.build
dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.html.json
dom/imptests/failures/html/html/dom/documents/dta/moz.build
dom/imptests/failures/html/html/dom/documents/dta/test_document.body-getter-frameset-and-body.html.json
dom/imptests/failures/html/html/dom/documents/dta/test_document.title-03.html.json
dom/imptests/failures/html/html/dom/documents/dta/test_document.title-04.xhtml.json
dom/imptests/failures/html/html/dom/documents/dta/test_document.title-06.html.json
dom/imptests/failures/html/html/dom/documents/dta/test_document.title-07.html.json
dom/imptests/failures/html/html/obsolete/implreq/oeaaa/Makefile.in
dom/imptests/failures/html/html/obsolete/implreq/oeaaa/moz.build
dom/imptests/failures/html/html/obsolete/implreq/oeaaa/test_script-IDL-event-htmlfor.html.json
dom/imptests/html/html/dom/documents/dta/Makefile.in
dom/imptests/html/html/dom/documents/dta/doc.gEBN/Makefile.in
dom/imptests/html/html/dom/documents/dta/doc.gEBN/moz.build
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-case.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-case.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-id.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-id.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-namespace.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-namespace.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-null-undef.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-null-undef.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-param.html
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-param.xhtml
dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-same.html
dom/imptests/html/html/dom/documents/dta/moz.build
dom/imptests/html/html/dom/documents/dta/test_Document.getElementsByClassName-null-undef.html
dom/imptests/html/html/dom/documents/dta/test_Element.getElementsByClassName-null-undef.html
dom/imptests/html/html/dom/documents/dta/test_document.body-getter-body-and-frameset.html
dom/imptests/html/html/dom/documents/dta/test_document.body-getter-foreign-frameset.html
dom/imptests/html/html/dom/documents/dta/test_document.body-getter-frameset-and-body.html
dom/imptests/html/html/dom/documents/dta/test_document.body-setter-01.html
dom/imptests/html/html/dom/documents/dta/test_document.embeds-document.plugins-01.html
dom/imptests/html/html/dom/documents/dta/test_document.getElementsByClassName-same.html
dom/imptests/html/html/dom/documents/dta/test_document.head-01.html
dom/imptests/html/html/dom/documents/dta/test_document.head-02.html
dom/imptests/html/html/dom/documents/dta/test_document.title-01.html
dom/imptests/html/html/dom/documents/dta/test_document.title-02.xhtml
dom/imptests/html/html/dom/documents/dta/test_document.title-03.html
dom/imptests/html/html/dom/documents/dta/test_document.title-04.xhtml
dom/imptests/html/html/dom/documents/dta/test_document.title-05.html
dom/imptests/html/html/dom/documents/dta/test_document.title-06.html
dom/imptests/html/html/dom/documents/dta/test_document.title-07.html
dom/imptests/html/html/dom/documents/dta/test_nameditem-01.html
dom/imptests/html/html/obsolete/implreq/oeaaa/Makefile.in
dom/imptests/html/html/obsolete/implreq/oeaaa/moz.build
dom/imptests/html/html/obsolete/implreq/oeaaa/test_document-color-01.html
dom/imptests/html/html/obsolete/implreq/oeaaa/test_document-color-02.html
dom/imptests/html/html/obsolete/implreq/oeaaa/test_document-color-03.html
dom/imptests/html/html/obsolete/implreq/oeaaa/test_document-color-04.html
dom/imptests/html/html/obsolete/implreq/oeaaa/test_heading-obsolete-attributes-01.html
dom/imptests/html/html/obsolete/implreq/oeaaa/test_script-IDL-event-htmlfor.html
layout/reftests/bidi/dirAuto/dir_auto-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-L.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-N-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-N-L.html
layout/reftests/bidi/dirAuto/dir_auto-N-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-N-R.html
layout/reftests/bidi/dirAuto/dir_auto-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-script-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-script-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-script-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-script-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-style-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-style-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-style-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-style-R.html
layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-L.html
layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-N-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-L-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-L.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-N-R.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-R-ref.html
layout/reftests/bidi/dirAuto/dir_auto-input-script-R.html
layout/reftests/bidi/dirAuto/dir_auto-isolate-ref.html
layout/reftests/bidi/dirAuto/dir_auto-isolate.html
layout/reftests/bidi/dirAuto/dir_auto-pre-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-pre-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-pre-N-between-Rs-ref.html
layout/reftests/bidi/dirAuto/dir_auto-pre-N-between-Rs.html
layout/reftests/bidi/dirAuto/dir_auto-pre-mixed-ref.html
layout/reftests/bidi/dirAuto/dir_auto-pre-mixed.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-N-between-Rs-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-N-between-Rs.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-mixed-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-mixed.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-EN-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-EN.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-between-Rs-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-between-Rs.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-mixed-ref.html
layout/reftests/bidi/dirAuto/dir_auto-textarea-script-mixed.html
layout/reftests/reftest.list
python/psutil/INSTALL
python/psutil/setup.cfg
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -2193,20 +2193,20 @@ nsDocument::RemoveStyleSheetsFromStyleSe
       }
     }
 
     // XXX Tell observers?
   }
 
 }
 
-nsresult
+void
 nsDocument::ResetStylesheetsToURI(nsIURI* aURI)
 {
-  NS_PRECONDITION(aURI, "Null URI passed to ResetStylesheetsToURI");
+  MOZ_ASSERT(aURI);
 
   mozAutoDocUpdate upd(this, UPDATE_STYLE, true);
   RemoveDocStyleSheetsFromStyleSets();
   RemoveStyleSheetsFromStyleSets(mCatalogSheets, nsStyleSet::eAgentSheet);
   RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eAgentSheet], nsStyleSet::eAgentSheet);
   RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eUserSheet], nsStyleSet::eUserSheet);
   RemoveStyleSheetsFromStyleSets(mAdditionalSheets[eAuthorSheet], nsStyleSet::eDocSheet);
 
@@ -2252,18 +2252,16 @@ nsDocument::ResetStylesheetsToURI(nsIURI
   // into style sets as needed.
   mStyleAttrStyleSheet->SetOwningDocument(this);
 
   // Now set up our style sets
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     FillStyleSet(shell->StyleSet());
   }
-
-  return NS_OK;
 }
 
 static bool
 AppendAuthorSheet(nsIStyleSheet *aSheet, void *aData)
 {
   nsStyleSet *styleSet = static_cast<nsStyleSet*>(aData);
   styleSet->AppendStyleSheet(nsStyleSet::eDocSheet, aSheet);
   return true;
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -1145,17 +1145,17 @@ protected:
   already_AddRefed<nsIPresShell> doCreateShell(nsPresContext* aContext,
                                                nsViewManager* aViewManager,
                                                nsStyleSet* aStyleSet,
                                                nsCompatibility aCompatMode);
 
   void RemoveDocStyleSheetsFromStyleSets();
   void RemoveStyleSheetsFromStyleSets(nsCOMArray<nsIStyleSheet>& aSheets, 
                                       nsStyleSet::sheetType aType);
-  nsresult ResetStylesheetsToURI(nsIURI* aURI);
+  void ResetStylesheetsToURI(nsIURI* aURI);
   void FillStyleSet(nsStyleSet* aStyleSet);
 
   // Return whether all the presshells for this document are safe to flush
   bool IsSafeToFlush() const;
 
   void DispatchPageTransition(mozilla::dom::EventTarget* aDispatchTarget,
                               const nsAString& aType,
                               bool aPersisted);
--- a/content/events/src/nsDOMUIEvent.cpp
+++ b/content/events/src/nsDOMUIEvent.cpp
@@ -219,40 +219,52 @@ nsDOMUIEvent::GetPagePoint()
 
   return pagePoint;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetPageX(int32_t* aPageX)
 {
   NS_ENSURE_ARG_POINTER(aPageX);
+  *aPageX = PageX();
+  return NS_OK;
+}
+
+int32_t
+nsDOMUIEvent::PageX() const
+{
   if (mPrivateDataDuplicated) {
-    *aPageX = mPagePoint.x;
-  } else {
-    *aPageX = nsDOMEvent::GetPageCoords(mPresContext,
-                                        mEvent,
-                                        mEvent->refPoint,
-                                        mClientPoint).x;
+    return mPagePoint.x;
   }
-  return NS_OK;
+
+  return nsDOMEvent::GetPageCoords(mPresContext,
+                                   mEvent,
+                                   mEvent->refPoint,
+                                   mClientPoint).x;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetPageY(int32_t* aPageY)
 {
   NS_ENSURE_ARG_POINTER(aPageY);
+  *aPageY = PageY();
+  return NS_OK;
+}
+
+int32_t
+nsDOMUIEvent::PageY() const
+{
   if (mPrivateDataDuplicated) {
-    *aPageY = mPagePoint.y;
-  } else {
-    *aPageY = nsDOMEvent::GetPageCoords(mPresContext,
-                                        mEvent,
-                                        mEvent->refPoint,
-                                        mClientPoint).y;
+    return mPagePoint.y;
   }
-  return NS_OK;
+
+  return nsDOMEvent::GetPageCoords(mPresContext,
+                                   mEvent,
+                                   mEvent->refPoint,
+                                   mClientPoint).y;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetWhich(uint32_t* aWhich)
 {
   NS_ENSURE_ARG_POINTER(aWhich);
   *aWhich = Which();
   return NS_OK;
@@ -294,30 +306,35 @@ nsDOMUIEvent::GetRangeParent(nsIDOMNode*
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetRangeOffset(int32_t* aRangeOffset)
 {
   NS_ENSURE_ARG_POINTER(aRangeOffset);
-  nsIFrame* targetFrame = nullptr;
+  *aRangeOffset = RangeOffset();
+  return NS_OK;
+}
 
-  if (mPresContext) {
-    targetFrame = mPresContext->EventStateManager()->GetEventTarget();
+int32_t
+nsDOMUIEvent::RangeOffset() const
+{
+  if (!mPresContext) {
+    return 0;
   }
 
-  if (targetFrame) {
-    nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mEvent,
-                                                              targetFrame);
-    *aRangeOffset = targetFrame->GetContentOffsetsFromPoint(pt).offset;
-    return NS_OK;
+  nsIFrame* targetFrame = mPresContext->EventStateManager()->GetEventTarget();
+  if (!targetFrame) {
+    return 0;
   }
-  *aRangeOffset = 0;
-  return NS_OK;
+
+  nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mEvent,
+                                                            targetFrame);
+  return targetFrame->GetContentOffsetsFromPoint(pt).offset;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetCancelBubble(bool* aCancelBubble)
 {
   NS_ENSURE_ARG_POINTER(aCancelBubble);
   *aCancelBubble = CancelBubble();
   return NS_OK;
@@ -326,17 +343,17 @@ nsDOMUIEvent::GetCancelBubble(bool* aCan
 NS_IMETHODIMP
 nsDOMUIEvent::SetCancelBubble(bool aCancelBubble)
 {
   mEvent->mFlags.mPropagationStopped = aCancelBubble;
   return NS_OK;
 }
 
 nsIntPoint
-nsDOMUIEvent::GetLayerPoint()
+nsDOMUIEvent::GetLayerPoint() const
 {
   if (!mEvent ||
       (mEvent->eventStructType != NS_MOUSE_EVENT &&
        mEvent->eventStructType != NS_MOUSE_SCROLL_EVENT &&
        mEvent->eventStructType != NS_WHEEL_EVENT &&
        mEvent->eventStructType != NS_TOUCH_EVENT &&
        mEvent->eventStructType != NS_DRAG_EVENT &&
        mEvent->eventStructType != NS_SIMPLE_GESTURE_EVENT) ||
@@ -368,28 +385,33 @@ nsDOMUIEvent::GetLayerY(int32_t* aLayerY
   NS_ENSURE_ARG_POINTER(aLayerY);
   *aLayerY = GetLayerPoint().y;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetIsChar(bool* aIsChar)
 {
-  switch(mEvent->eventStructType)
+  *aIsChar = IsChar();
+  return NS_OK;
+}
+
+bool
+nsDOMUIEvent::IsChar() const
+{
+  switch (mEvent->eventStructType)
   {
     case NS_KEY_EVENT:
-      *aIsChar = ((nsKeyEvent*)mEvent)->isChar;
-      return NS_OK;
+      return static_cast<nsKeyEvent*>(mEvent)->isChar;
     case NS_TEXT_EVENT:
-      *aIsChar = ((nsTextEvent*)mEvent)->isChar;
-      return NS_OK;
+      return static_cast<nsKeyEvent*>(mEvent)->isChar;
     default:
-      *aIsChar = false;
-      return NS_OK;
+      return false;
   }
+  MOZ_NOT_REACHED("Switch handles all cases.");
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::DuplicatePrivateData()
 {
   mClientPoint = nsDOMEvent::GetClientCoords(mPresContext,
                                              mEvent,
                                              mEvent->refPoint,
--- a/content/events/src/nsDOMUIEvent.h
+++ b/content/events/src/nsDOMUIEvent.h
@@ -93,86 +93,64 @@ public:
                                                     mozilla::ErrorResult& aRv);
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return mozilla::dom::UIEventBinding::Wrap(aCx, aScope, this);
   }
 
-  already_AddRefed<nsIDOMWindow> GetView()
+  nsIDOMWindow* GetView() const
   {
-    nsCOMPtr<nsIDOMWindow> view = mView;
-    return view.forget();
+    return mView;
   }
 
-  int32_t Detail()
+  int32_t Detail() const
   {
     return mDetail;
   }
 
-  int32_t LayerX()
+  int32_t LayerX() const
   {
     return GetLayerPoint().x;
   }
 
-  int32_t LayerY()
+  int32_t LayerY() const
   {
     return GetLayerPoint().y;
   }
 
-  int32_t PageX()
-  {
-    int32_t x;
-    GetPageX(&x);
-    return x;
-  }
-
-  int32_t PageY()
-  {
-    int32_t y;
-    GetPageY(&y);
-    return y;
-  }
+  int32_t PageX() const;
+  int32_t PageY() const;
 
   virtual uint32_t Which()
   {
     MOZ_ASSERT(mEvent->eventStructType != NS_KEY_EVENT,
                "Key events should override Which()");
     MOZ_ASSERT(mEvent->eventStructType != NS_MOUSE_EVENT,
                "Mouse events should override Which()");
     return 0;
   }
 
   already_AddRefed<nsINode> GetRangeParent();
 
-  int32_t RangeOffset()
-  {
-    int32_t offset;
-    GetRangeOffset(&offset);
-    return offset;
-  }
+  int32_t RangeOffset() const;
 
-  bool CancelBubble()
+  bool CancelBubble() const
   {
     return mEvent->mFlags.mPropagationStopped;
   }
 
-  bool IsChar()
-  {
-    bool isChar;
-    GetIsChar(&isChar);
-    return isChar;
-  }
+  bool IsChar() const;
 
 protected:
   // Internal helper functions
   nsIntPoint GetClientPoint();
   nsIntPoint GetMovementPoint();
-  nsIntPoint GetLayerPoint();
+  nsIntPoint GetLayerPoint() const;
   nsIntPoint GetPagePoint();
 
   nsCOMPtr<nsIDOMWindow> mView;
   int32_t mDetail;
   nsIntPoint mClientPoint;
   // Screenpoint is mEvent->refPoint.
   nsIntPoint mLayerPoint;
   nsIntPoint mPagePoint;
--- a/content/html/content/reftests/reftest.list
+++ b/content/html/content/reftests/reftest.list
@@ -19,21 +19,13 @@ skip-if(B2G) == 41464-1b.html 41464-1-re
 == 596455-1a.html 596455-ref-1.html
 == 596455-1b.html 596455-ref-1.html
 == 596455-2a.html 596455-ref-2.html
 == 596455-2b.html 596455-ref-2.html
 == 610935.html 610935-ref.html
 == 649134-1.html 649134-ref.html
 skip-if(Android||B2G) == 649134-2.html 649134-2-ref.html
 
-== hidden-1a.html hidden-1-ref.html
-== hidden-1b.html hidden-1-ref.html
-== hidden-1c.html hidden-1-ref.html
-== hidden-1d.html hidden-1-ref.html
-== hidden-1e.html hidden-1-ref.html
-== hidden-1f.html hidden-1-ref.html
-== hidden-1g.html hidden-1-ref.html
-== hidden-2.svg hidden-2-ref.svg
 == href-attr-change-restyles.html href-attr-change-restyles-ref.html
 == figure.html figure-ref.html
 == table-border-1.html table-border-1-ref.html
 == table-border-2.html table-border-2-ref.html
 != table-border-2.html table-border-2-notref.html
--- a/content/xul/document/src/XULDocument.cpp
+++ b/content/xul/document/src/XULDocument.cpp
@@ -428,18 +428,17 @@ XULDocument::StartDocumentLoad(const cha
 
     mHaveInputEncoding = true;
 
     // Get the URI.  Note that this should match nsDocShell::OnLoadingSite
     nsresult rv =
         NS_GetFinalChannelURI(aChannel, getter_AddRefs(mDocumentURI));
     NS_ENSURE_SUCCESS(rv, rv);
     
-    rv = ResetStylesheetsToURI(mDocumentURI);
-    if (NS_FAILED(rv)) return rv;
+    ResetStylesheetsToURI(mDocumentURI);
 
     RetrieveRelevantHeaders(aChannel);
 
     // Look in the chrome cache: we've got this puppy loaded
     // already.
     nsXULPrototypeDocument* proto = IsChromeURI(mDocumentURI) ?
             nsXULPrototypeCache::GetInstance()->GetPrototype(mDocumentURI) :
             nullptr;
--- a/dom/imptests/editing.txt
+++ b/dom/imptests/editing.txt
@@ -1,2 +1,2 @@
-https://dvcs.w3.org/hg/editing|editing
+hg|https://dvcs.w3.org/hg/editing|editing
 
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/browsers/the-window-object/named-access-on-the-window-object/Makefile.in
@@ -0,0 +1,16 @@
+# THIS FILE IS AUTOGENERATED BY parseFailures.py - DO NOT EDIT
+
+DEPTH := @DEPTH@
+
+topsrcdir := @top_srcdir@
+srcdir := @srcdir@
+VPATH := @srcdir@
+relativesrcdir := @relativesrcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MOCHITEST_FILES := \
+  test_window-null-names.html.json \
+  $(NULL)
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/browsers/the-window-object/named-access-on-the-window-object/moz.build
@@ -0,0 +1,4 @@
+# THIS FILE IS AUTOGENERATED BY parseFailures.py - DO NOT EDIT
+
+DIRS += [
+]
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/browsers/the-window-object/named-access-on-the-window-object/test_window-null-names.html.json
@@ -0,0 +1,3 @@
+{
+  "Named access with null characters": true
+}
--- a/dom/imptests/failures/html/html/dom/documents/dta/Makefile.in
+++ b/dom/imptests/failures/html/html/dom/documents/dta/Makefile.in
@@ -5,16 +5,21 @@ DEPTH := @DEPTH@
 topsrcdir := @top_srcdir@
 srcdir := @srcdir@
 VPATH := @srcdir@
 relativesrcdir := @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MOCHITEST_FILES := \
-  test_document.body-getter-frameset-and-body.html.json \
+  test_document.body-getter.html.json \
   test_document.title-03.html.json \
   test_document.title-04.xhtml.json \
   test_document.title-06.html.json \
   test_document.title-07.html.json \
+  test_nameditem-02.html.json \
+  test_nameditem-03.html.json \
+  test_nameditem-04.html.json \
+  test_nameditem-05.html.json \
+  test_nameditem-06.html.json \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/Makefile.in
+++ b/dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/Makefile.in
@@ -5,12 +5,12 @@ DEPTH := @DEPTH@
 topsrcdir := @top_srcdir@
 srcdir := @srcdir@
 VPATH := @srcdir@
 relativesrcdir := @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MOCHITEST_FILES := \
-  test_doc.gEBN-newelements.html.json \
+  test_document.getElementsByName-newelements.html.json \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
rename from dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.html.json
rename to dom/imptests/failures/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-newelements.html.json
rename from dom/imptests/failures/html/html/dom/documents/dta/test_document.body-getter-frameset-and-body.html.json
rename to dom/imptests/failures/html/html/dom/documents/dta/test_document.body-getter.html.json
--- a/dom/imptests/failures/html/html/dom/documents/dta/test_document.body-getter-frameset-and-body.html.json
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_document.body-getter.html.json
@@ -1,3 +1,8 @@
 {
-  "document.body and framesets": true
+  "Frameset followed by body inside the html element": true,
+  "Body followed by frameset inside a non-HTML html element": true,
+  "Frameset inside an x element followed by a frameset": true,
+  "Frameset as the root node": true,
+  "Body as the root node with a frameset child": true,
+  "Frameset as the root node with a body child": true
 }
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_nameditem-02.html.json
@@ -0,0 +1,8 @@
+{
+  "If the only named item is an iframe, the contentWindow should be returned.": true,
+  "If there are two iframes, a collection should be returned.": true,
+  "If there are an iframe and another element (iframe first), a collection should be returned.": true,
+  "If there are an iframe and another element (iframe last), a collection should be returned.": true,
+  "If an iframe has a name and a different id, it should be returned by its name.": true,
+  "An iframe whose name looks like an array index should work.": true
+}
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_nameditem-03.html.json
@@ -0,0 +1,6 @@
+{
+  "If there are two applets, a collection should be returned. (name)": true,
+  "If there are two applets, a collection should be returned. (id)": true,
+  "If there are two applets, a collection should be returned. (name and id)": true,
+  "If there are two applets, a collection should be returned. (id and name)": true
+}
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_nameditem-04.html.json
@@ -0,0 +1,3 @@
+{
+  "If there are two forms, a collection should be returned. (name)": true
+}
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_nameditem-05.html.json
@@ -0,0 +1,6 @@
+{
+  "If there are two embeds, a collection should be returned. (name)": true,
+  "If there is one embed, it should not be returned (id)": true,
+  "If there are two embeds, nothing should be returned. (id)": true,
+  "A name shouldn't affect getting an embed by id": true
+}
new file mode 100644
--- /dev/null
+++ b/dom/imptests/failures/html/html/dom/documents/dta/test_nameditem-06.html.json
@@ -0,0 +1,5 @@
+{
+  "If there are two imgs, a collection should be returned. (name)": true,
+  "If there is one img, it should not be returned (id)": true,
+  "If there are two imgs, nothing should be returned. (id)": true
+}
--- a/dom/imptests/failures/html/html/semantics/scripting-1/the-script-element/moz.build
+++ b/dom/imptests/failures/html/html/semantics/scripting-1/the-script-element/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY parseFailures.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/failures/html/old-tests/submission/Opera/microdata/moz.build
+++ b/dom/imptests/failures/html/old-tests/submission/Opera/microdata/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY parseFailures.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/html.mozbuild
+++ b/dom/imptests/html.mozbuild
@@ -1,15 +1,17 @@
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
     'html/domxpath',
     'html/html/browsers/browsing-the-web/read-media',
     'html/html/browsers/the-window-object',
+    'html/html/browsers/the-window-object/named-access-on-the-window-object',
     'html/html/dom/documents/dta',
+    'html/html/dom/documents/dta/doc.gEBN',
     'html/html/dom/elements/global-attributes',
     'html/html/editing/the-hidden-attribute',
     'html/html/obsolete/implreq/oeaaa',
     'html/html/semantics/document-metadata/the-title-element',
     'html/html/semantics/forms/the-form-element',
     'html/html/semantics/forms/the-option-element',
     'html/html/semantics/forms/the-select-element',
     'html/html/semantics/scripting-1/the-script-element',
--- a/dom/imptests/html.txt
+++ b/dom/imptests/html.txt
@@ -1,16 +1,16 @@
-git+ssh://git@github.com:w3c/web-platform-tests.git|html
+git|git://github.com/w3c/web-platform-tests.git|html
 domxpath
 html/browsers/browsing-the-web/read-media
 html/browsers/the-window-object
-html/dom/documents/dta
+html/dom/documents/dom-tree-accessors
 html/dom/elements/global-attributes
 html/editing/the-hidden-attribute
-html/obsolete/implreq/oeaaa
+html/obsolete/requirements-for-implementations/other-elements-attributes-and-apis
 html/semantics/document-metadata/the-title-element
 html/semantics/forms/the-form-element
 html/semantics/forms/the-option-element
 html/semantics/forms/the-select-element
 html/semantics/scripting-1/the-script-element
 html/semantics/tabular-data/the-table-element
 html/semantics/text-level-semantics/the-time-element
 html/webappapis/atob
--- a/dom/imptests/html/html/browsers/browsing-the-web/read-media/moz.build
+++ b/dom/imptests/html/html/browsers/browsing-the-web/read-media/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
 ]
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/browsers/the-window-object/named-access-on-the-window-object/Makefile.in
@@ -0,0 +1,16 @@
+# THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
+
+DEPTH := @DEPTH@
+
+topsrcdir := @top_srcdir@
+srcdir := @srcdir@
+VPATH := @srcdir@
+relativesrcdir := @relativesrcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MOCHITEST_FILES := \
+  test_window-null-names.html \
+  $(NULL)
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/browsers/the-window-object/named-access-on-the-window-object/moz.build
@@ -0,0 +1,4 @@
+# THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
+
+DIRS += [
+]
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/browsers/the-window-object/named-access-on-the-window-object/test_window-null-names.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Named access with null characters</title>
+<link rel="author" title="Ms2ger" href="ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#window">
+<link rel="help" href="http://www.whatwg.org/html/#dom-window-nameditem">
+<link rel="help" href="http://dev.w3.org/2006/webapi/WebIDL/#named-properties-object">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+test(function() {
+  var iframe = document.createElement("iframe")
+  iframe.name = "a\0b"
+  document.body.appendChild(iframe)
+  assert_equals(window["a\0b"], iframe.contentWindow)
+  assert_equals(window["ab"], undefined)
+  assert_equals(window["a"], undefined)
+});
+</script>
--- a/dom/imptests/html/html/browsers/the-window-object/test_window-named-properties.html
+++ b/dom/imptests/html/html/browsers/the-window-object/test_window-named-properties.html
@@ -46,17 +46,17 @@ test(function() {
   var gsp = Object.getPrototypeOf(proto);
   assert_true("constructor" in gsp, "constructor in gsp");
   assert_true(gsp.hasOwnProperty("constructor"), "gsp.hasOwnProperty(\"constructor\")");
   assert_data_propdesc(Object.getOwnPropertyDescriptor(gsp, "constructor"),
                        false, true, true);
 }, "constructor");
 var t = async_test("Dynamic name")
 var t2 = async_test("Ghost name")
-window.onload = t.step_func(function() {
+t.step(function() {
   var iframe = document.getElementsByTagName("iframe")[0];
   iframe.setAttribute("src", "data:text/html,<script>window.name='foo'<\/script>");
   iframe.onload = function() {
     t.step(function() {
       assert_true("foo" in window, "foo not in window");
       assert_equals(window["foo"], iframe.contentWindow);
     });
     t.done();
--- a/dom/imptests/html/html/dom/documents/dta/Makefile.in
+++ b/dom/imptests/html/html/dom/documents/dta/Makefile.in
@@ -5,29 +5,32 @@ DEPTH := @DEPTH@
 topsrcdir := @top_srcdir@
 srcdir := @srcdir@
 VPATH := @srcdir@
 relativesrcdir := @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MOCHITEST_FILES := \
-  test_document.body-getter-body-and-frameset.html \
-  test_document.body-getter-foreign-frameset.html \
-  test_document.body-getter-frameset-and-body.html \
+  test_document.body-getter.html \
   test_document.body-setter-01.html \
   test_document.embeds-document.plugins-01.html \
   test_Document.getElementsByClassName-null-undef.html \
   test_document.getElementsByClassName-same.html \
   test_document.head-01.html \
   test_document.head-02.html \
   test_document.title-01.html \
   test_document.title-02.xhtml \
   test_document.title-03.html \
   test_document.title-04.xhtml \
   test_document.title-05.html \
   test_document.title-06.html \
   test_document.title-07.html \
   test_Element.getElementsByClassName-null-undef.html \
   test_nameditem-01.html \
+  test_nameditem-02.html \
+  test_nameditem-03.html \
+  test_nameditem-04.html \
+  test_nameditem-05.html \
+  test_nameditem-06.html \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/dom/imptests/html/html/dom/documents/dta/doc.gEBN/Makefile.in
+++ b/dom/imptests/html/html/dom/documents/dta/doc.gEBN/Makefile.in
@@ -5,24 +5,24 @@ DEPTH := @DEPTH@
 topsrcdir := @top_srcdir@
 srcdir := @srcdir@
 VPATH := @srcdir@
 relativesrcdir := @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MOCHITEST_FILES := \
-  test_doc.gEBN-case.html \
-  test_doc.gEBN-case.xhtml \
-  test_doc.gEBN-id.html \
-  test_doc.gEBN-id.xhtml \
-  test_doc.gEBN-namespace.html \
-  test_doc.gEBN-namespace.xhtml \
-  test_doc.gEBN-newelements.html \
-  test_doc.gEBN-newelements.xhtml \
-  test_doc.gEBN-null-undef.html \
-  test_doc.gEBN-null-undef.xhtml \
-  test_doc.gEBN-param.html \
-  test_doc.gEBN-param.xhtml \
-  test_doc.gEBN-same.html \
+  test_document.getElementsByName-case.html \
+  test_document.getElementsByName-case.xhtml \
+  test_document.getElementsByName-id.html \
+  test_document.getElementsByName-id.xhtml \
+  test_document.getElementsByName-namespace.html \
+  test_document.getElementsByName-namespace.xhtml \
+  test_document.getElementsByName-newelements.html \
+  test_document.getElementsByName-newelements.xhtml \
+  test_document.getElementsByName-null-undef.html \
+  test_document.getElementsByName-null-undef.xhtml \
+  test_document.getElementsByName-param.html \
+  test_document.getElementsByName-param.xhtml \
+  test_document.getElementsByName-same.html \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-case.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-case.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-case.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-case.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-id.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-id.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-id.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-id.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-namespace.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-namespace.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-namespace.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-namespace.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-newelements.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-newelements.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-newelements.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-null-undef.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-null-undef.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-null-undef.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-null-undef.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-param.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-param.html
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-param.xhtml
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-param.xhtml
rename from dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_doc.gEBN-same.html
rename to dom/imptests/html/html/dom/documents/dta/doc.gEBN/test_document.getElementsByName-same.html
--- a/dom/imptests/html/html/dom/documents/dta/moz.build
+++ b/dom/imptests/html/html/dom/documents/dta/moz.build
@@ -1,5 +1,4 @@
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
-    'doc.gEBN',
 ]
deleted file mode 100644
--- a/dom/imptests/html/html/dom/documents/dta/test_document.body-getter-body-and-frameset.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<title>document.body and framesets</title>
-<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
-<link rel="help" href="http://www.whatwg.org/html5/#dom-document-body">
-<link rel="stylesheet" href="/resources/testharness.css">
-<script src="/resources/testharness.js"></script>
-<script src="/resources/testharnessreport.js"></script>
-<script>
-var b =
-  document.documentElement.appendChild(document.createElement("body"));
-document.documentElement.appendChild(document.createElement("frameset"));
-</script>
-<div id="log"></div>
-<script>
-test(function() {
-  assert_equals(document.body, b);
-});
-</script>
deleted file mode 100644
--- a/dom/imptests/html/html/dom/documents/dta/test_document.body-getter-foreign-frameset.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE html>
-<title>document.body and a frameset in a foreign namespace</title>
-<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
-<link rel="help" href="http://www.whatwg.org/html5/#dom-document-body">
-<link rel="stylesheet" href="/resources/testharness.css">
-<script src="/resources/testharness.js"></script>
-<script src="/resources/testharnessreport.js"></script>
-<script>
-document.documentElement.appendChild(
-  document.createElementNS("http://example.org/test", "frameset"));
-</script>
-<div id="log"></div>
-<script>
-test(function() {
-  assert_equals(document.body, document.getElementsByTagName("body")[0]);
-});
-</script>
deleted file mode 100644
--- a/dom/imptests/html/html/dom/documents/dta/test_document.body-getter-frameset-and-body.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<title>document.body and framesets</title>
-<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
-<link rel="help" href="http://www.whatwg.org/html5/#dom-document-body">
-<link rel="stylesheet" href="/resources/testharness.css">
-<script src="/resources/testharness.js"></script>
-<script src="/resources/testharnessreport.js"></script>
-<script>
-var f =
-  document.documentElement.appendChild(document.createElement("frameset"));
-document.documentElement.appendChild(document.createElement("body"));
-</script>
-<div id="log"></div>
-<script>
-test(function() {
-  assert_equals(document.body, f);
-});
-</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_document.body-getter.html
@@ -0,0 +1,125 @@
+<!DOCTYPE html>
+<title>Document.body</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-body">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<script>
+</script>
+<div id="log"></div>
+<script>
+function createDocument() {
+  var doc = document.implementation.createHTMLDocument("");
+  doc.removeChild(doc.documentElement);
+  return doc;
+}
+test(function() {
+  var doc = createDocument();
+  assert_equals(doc.body, null);
+}, "Childless document");
+test(function() {
+  var doc = createDocument();
+  doc.appendChild(doc.createElement("html"));
+  assert_equals(doc.body, null);
+}, "Childless html element");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  var b =
+    html.appendChild(doc.createElement("body"));
+  html.appendChild(doc.createElement("frameset"));
+  assert_equals(doc.body, b);
+}, "Body followed by frameset inside the html element");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  var f =
+    html.appendChild(doc.createElement("frameset"));
+  html.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, f);
+}, "Frameset followed by body inside the html element");
+test(function() {
+  var doc = createDocument();
+  var html =
+    doc.appendChild(doc.createElementNS("http://example.org/test", "html"));
+  var b =
+    html.appendChild(doc.createElement("body"));
+  html.appendChild(doc.createElement("frameset"));
+  assert_equals(doc.body, b);
+}, "Body followed by frameset inside a non-HTML html element");
+test(function() {
+  var doc = createDocument();
+  var html =
+    doc.appendChild(doc.createElementNS("http://example.org/test", "html"));
+  var f =
+    html.appendChild(doc.createElement("frameset"));
+  html.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, f);
+}, "Frameset followed by body inside a non-HTML html element");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  html.appendChild(
+    doc.createElementNS("http://example.org/test", "body"));
+  var b = html.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, b);
+}, "Non-HTML body followed by body inside the html element");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  html.appendChild(
+    doc.createElementNS("http://example.org/test", "frameset"));
+  var b = html.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, b);
+}, "Non-HTML frameset followed by body inside the html element");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  var x = html.appendChild(doc.createElement("x"));
+  x.appendChild(doc.createElement("body"));
+  var body = html.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, body);
+}, "Body inside an x element followed by a body");
+test(function() {
+  var doc = createDocument();
+  var html = doc.appendChild(doc.createElement("html"));
+  var x = html.appendChild(doc.createElement("x"));
+  x.appendChild(doc.createElement("frameset"));
+  var frameset = html.appendChild(doc.createElement("frameset"));
+  assert_equals(doc.body, frameset);
+}, "Frameset inside an x element followed by a frameset");
+
+// Root node is not a html element.
+test(function() {
+  var doc = createDocument();
+  doc.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, null);
+}, "Body as the root node");
+test(function() {
+  var doc = createDocument();
+  doc.appendChild(doc.createElement("frameset"));
+  assert_equals(doc.body, null);
+}, "Frameset as the root node");
+test(function() {
+  var doc = createDocument();
+  var body = doc.appendChild(doc.createElement("body"));
+  body.appendChild(doc.createElement("frameset"));
+  assert_equals(doc.body, null);
+}, "Body as the root node with a frameset child");
+test(function() {
+  var doc = createDocument();
+  var frameset = doc.appendChild(doc.createElement("frameset"));
+  frameset.appendChild(doc.createElement("body"));
+  assert_equals(doc.body, null);
+}, "Frameset as the root node with a body child");
+test(function() {
+  var doc = createDocument();
+  doc.appendChild(doc.createElementNS("http://example.org/test", "body"));
+  assert_equals(doc.body, null);
+}, "Non-HTML body as the root node");
+test(function() {
+  var doc = createDocument();
+  doc.appendChild(doc.createElementNS("http://example.org/test", "frameset"));
+  assert_equals(doc.body, null);
+}, "Non-HTML frameset as the root node");
+</script>
--- a/dom/imptests/html/html/dom/documents/dta/test_document.body-setter-01.html
+++ b/dom/imptests/html/html/dom/documents/dta/test_document.body-setter-01.html
@@ -1,17 +1,27 @@
 <!DOCTYPE html>
 <title>Setting document.body to incorrect values</title>
 <link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
-<link rel="help" href="http://www.whatwg.org/html5/#dom-document-body">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-body">
 <link rel="help" href="http://dev.w3.org/2006/webapi/WebIDL/#es-interface">
-<link rel="stylesheet" href="/resources/testharness.css">
 <script src="/resources/testharness.js"></script>
 <script src="/resources/testharnessreport.js"></script>
 <div id="log"></div>
 <script>
 test(function() {
-  assert_throws(new TypeError(), function() { document.body = "text" })
-}, "Should throw a TypeError.");
+  assert_throws(new TypeError(), function() {
+    document.body = "text"
+  })
+}, "Should throw a TypeError when trying to set document.body to a string.")
 test(function() {
-  assert_throws("HIERARCHY_REQUEST_ERR", function() { document.body = document.createElement("div") })
-}, "Should throw a HIERARCHY_REQUEST_ERR.");
+  assert_throws("HierarchyRequestError", function() {
+    document.body = document.createElement("div")
+  })
+}, "Should throw a HierarchyRequestError when trying to set document.body to a div element.")
+test(function() {
+  var doc = document.implementation.createHTMLDocument("")
+  doc.removeChild(doc.documentElement)
+  assert_throws("HierarchyRequestError", function() {
+    doc.body = document.createElement("body")
+  })
+}, "Should throw a HierarchyRequestError when trying to set document.body when there's no root element.")
 </script>
--- a/dom/imptests/html/html/dom/documents/dta/test_nameditem-01.html
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-01.html
@@ -1,19 +1,19 @@
 <!DOCTYPE html>
+<meta charset=utf-8>
 <title>Named items: img id &amp; name</title>
 <link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
-<link rel="help" href="http://www.whatwg.org/html5/#dom-document-nameditem">
-<link rel="stylesheet" href="/resources/testharness.css">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
 <script src="/resources/testharness.js"></script>
 <script src="/resources/testharnessreport.js"></script>
 <div id="log"></div>
 <div id="test">
 <img id="a" name="b">
 </div>
 <script>
 test(function() {
   assert_equals(document.a, document.getElementsByTagName("img")[0]);
   assert_equals(document['a'], document.getElementsByTagName("img")[0]);
   assert_equals(document.b, document.getElementsByTagName("img")[0]);
   assert_equals(document['b'], document.getElementsByTagName("img")[0]);
-});
+}, "img elements that have a name and id attribute, should be accessible by both values.");
 </script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-02.html
@@ -0,0 +1,99 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Named items: iframes</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<div id="test">
+<iframe name="test1"></iframe>
+
+<iframe name="test2"></iframe>
+<iframe name="test2"></iframe>
+
+<iframe name="test3"></iframe>
+<img name="test3">
+
+<img name="test4">
+<iframe name="test4"></iframe>
+
+<iframe id="test5"></iframe>
+
+<iframe name="test6" id="fail"></iframe>
+
+<iframe name="fail" id="test7"></iframe>
+
+<iframe name="42"></iframe>
+</div>
+<script>
+test(function() {
+  var iframe = document.getElementsByTagName("iframe")[0];
+  assert_equals(iframe.name, "test1");
+
+  assert_true("test1" in document, '"test1" in document should be true');
+  assert_equals(document.test1, iframe.contentWindow);
+}, "If the only named item is an iframe, the contentWindow should be returned.");
+
+test(function() {
+  var iframe1 = document.getElementsByTagName("iframe")[1];
+  assert_equals(iframe1.name, "test2");
+  var iframe2 = document.getElementsByTagName("iframe")[2];
+  assert_equals(iframe2.name, "test2");
+
+  assert_true("test2" in document, '"test2" in document should be true');
+  var collection = document.test2;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [iframe1, iframe2]);
+}, "If there are two iframes, a collection should be returned.");
+
+test(function() {
+  var iframe = document.getElementsByTagName("iframe")[3];
+  assert_equals(iframe.name, "test3");
+  var img = document.getElementsByTagName("img")[0];
+  assert_equals(img.name, "test3");
+
+  assert_true("test3" in document, '"test3" in document should be true');
+  var collection = document.test3;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [iframe, img]);
+}, "If there are an iframe and another element (iframe first), a collection should be returned.");
+
+test(function() {
+  var iframe = document.getElementsByTagName("iframe")[4];
+  assert_equals(iframe.name, "test4");
+  var img = document.getElementsByTagName("img")[1];
+  assert_equals(img.name, "test4");
+
+  assert_true("test4" in document, '"test4" in document should be true');
+  var collection = document.test4;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [img, iframe]);
+}, "If there are an iframe and another element (iframe last), a collection should be returned.");
+
+test(function() {
+  assert_false("test5" in document, '"test5" in document should be false');
+  assert_equals(document.test5, undefined);
+}, "If an iframe has an id and no name, it should not be returned.");
+
+test(function() {
+  var iframe = document.getElementsByTagName("iframe")[6];
+  assert_equals(iframe.name, "test6");
+
+  assert_true("test6" in document, '"test6" in document should be true');
+  assert_equals(document.test6, iframe.contentWindow);
+}, "If an iframe has a name and a different id, it should be returned by its name.");
+
+test(function() {
+  assert_false("test7" in document, '"test7" in document should be false');
+  assert_equals(document.test7, undefined);
+}, "If an iframe has an id and a different name, it should not be returned by its id.");
+
+test(function() {
+  var iframe = document.getElementsByTagName("iframe")[8];
+  assert_equals(iframe.name, "42");
+
+  assert_true(42 in document, '42 in document should be true');
+  assert_equals(document[42], iframe.contentWindow);
+}, "An iframe whose name looks like an array index should work.");
+</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-03.html
@@ -0,0 +1,110 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Named items: applets</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<div id="test">
+<applet name=test1></applet>
+
+<applet name=test2></applet>
+<applet name=test2></applet>
+
+<applet id=test3></applet>
+
+<applet id=test4></applet>
+<applet id=test4></applet>
+
+<applet name=test5></applet>
+<applet id=test5></applet>
+
+<applet id=test6></applet>
+<applet name=test6></applet>
+
+<applet id=test7 name=fail></applet>
+
+<applet name=test8 id=fail></applet>
+</div>
+<script>
+test(function() {
+  var applet = document.getElementsByTagName("applet")[0];
+  assert_equals(applet.name, "test1");
+
+  assert_true("test1" in document, '"test1" in document should be true');
+  assert_equals(document.test1, applet);
+}, "If there is one applet, it should be returned (name)");
+
+test(function() {
+  var applet1 = document.getElementsByTagName("applet")[1];
+  assert_equals(applet1.name, "test2");
+  var applet2 = document.getElementsByTagName("applet")[2];
+  assert_equals(applet2.name, "test2");
+
+  assert_true("test2" in document, '"test2" in document should be true');
+  var collection = document.test2;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [applet1, applet2]);
+}, "If there are two applets, a collection should be returned. (name)");
+
+test(function() {
+  var applet = document.getElementsByTagName("applet")[3];
+  assert_equals(applet.id, "test3");
+
+  assert_true("test3" in document, '"test3" in document should be true');
+  assert_equals(document.test3, applet);
+}, "If there is one applet, it should be returned (id)");
+
+test(function() {
+  var applet1 = document.getElementsByTagName("applet")[4];
+  assert_equals(applet1.id, "test4");
+  var applet2 = document.getElementsByTagName("applet")[5];
+  assert_equals(applet2.id, "test4");
+
+  assert_true("test4" in document, '"test4" in document should be true');
+  var collection = document.test4;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [applet1, applet2]);
+}, "If there are two applets, a collection should be returned. (id)");
+
+test(function() {
+  var applet1 = document.getElementsByTagName("applet")[6];
+  assert_equals(applet1.name, "test5");
+  var applet2 = document.getElementsByTagName("applet")[7];
+  assert_equals(applet2.id, "test5");
+
+  assert_true("test5" in document, '"test5" in document should be true');
+  var collection = document.test5;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [applet1, applet2]);
+}, "If there are two applets, a collection should be returned. (name and id)");
+
+test(function() {
+  var applet1 = document.getElementsByTagName("applet")[8];
+  assert_equals(applet1.id, "test6");
+  var applet2 = document.getElementsByTagName("applet")[9];
+  assert_equals(applet2.name, "test6");
+
+  assert_true("test6" in document, '"test6" in document should be true');
+  var collection = document.test6;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [applet1, applet2]);
+}, "If there are two applets, a collection should be returned. (id and name)");
+
+test(function() {
+  var applet = document.getElementsByTagName("applet")[10];
+  assert_equals(applet.id, "test7");
+
+  assert_true("test7" in document, '"test7" in document should be true');
+  assert_equals(document.test7, applet);
+}, "A name shouldn't affect getting an applet by id");
+
+test(function() {
+  var applet = document.getElementsByTagName("applet")[11];
+  assert_equals(applet.name, "test8");
+
+  assert_true("test8" in document, '"test8" in document should be true');
+  assert_equals(document.test8, applet);
+}, "An id shouldn't affect getting an applet by name");
+</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-04.html
@@ -0,0 +1,104 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Named items: forms</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<div id="test">
+<form name=test1></form>
+
+<form name=test2></form>
+<form name=test2></form>
+
+<form id=test3></form>
+
+<form id=test4></form>
+<form id=test4></form>
+
+<form name=test5></form>
+<form id=test5></form>
+
+<form id=test6></form>
+<form name=test6></form>
+
+<form id=test7 name=fail></form>
+
+<form name=test8 id=fail></form>
+</div>
+<script>
+test(function() {
+  var form = document.getElementsByTagName("form")[0];
+  assert_equals(form.name, "test1");
+
+  assert_true("test1" in document, '"test1" in document should be true');
+  assert_equals(document.test1, form);
+}, "If there is one form, it should be returned (name)");
+
+test(function() {
+  var form1 = document.getElementsByTagName("form")[1];
+  assert_equals(form1.name, "test2");
+  var form2 = document.getElementsByTagName("form")[2];
+  assert_equals(form2.name, "test2");
+
+  assert_true("test2" in document, '"test2" in document should be true');
+  var collection = document.test2;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [form1, form2]);
+}, "If there are two forms, a collection should be returned. (name)");
+
+test(function() {
+  var form = document.getElementsByTagName("form")[3];
+  assert_equals(form.id, "test3");
+
+  assert_false("test3" in document, '"test3" in document should be false');
+  assert_equals(document.test3, undefined);
+}, "If there is one form, it should not be returned (id)");
+
+test(function() {
+  var form1 = document.getElementsByTagName("form")[4];
+  assert_equals(form1.id, "test4");
+  var form2 = document.getElementsByTagName("form")[5];
+  assert_equals(form2.id, "test4");
+
+  assert_false("test4" in document, '"test4" in document should be false');
+  assert_equals(document.test4, undefined);
+}, "If there are two forms, nothing should be returned. (id)");
+
+test(function() {
+  var form1 = document.getElementsByTagName("form")[6];
+  assert_equals(form1.name, "test5");
+  var form2 = document.getElementsByTagName("form")[7];
+  assert_equals(form2.id, "test5");
+
+  assert_true("test5" in document, '"test5" in document should be true');
+  assert_equals(document.test5, form1);
+}, "If there are two forms, a collection should be returned. (name and id)");
+
+test(function() {
+  var form1 = document.getElementsByTagName("form")[8];
+  assert_equals(form1.id, "test6");
+  var form2 = document.getElementsByTagName("form")[9];
+  assert_equals(form2.name, "test6");
+
+  assert_true("test6" in document, '"test6" in document should be true');
+  assert_equals(document.test6, form2);
+}, "If there are two forms, a collection should be returned. (id and name)");
+
+test(function() {
+  var form = document.getElementsByTagName("form")[10];
+  assert_equals(form.id, "test7");
+
+  assert_false("test7" in document, '"test7" in document should be false');
+  assert_equals(document.test7, undefined);
+}, "A name shouldn't affect getting an form by id");
+
+test(function() {
+  var form = document.getElementsByTagName("form")[11];
+  assert_equals(form.name, "test8");
+
+  assert_true("test8" in document, '"test8" in document should be true');
+  assert_equals(document.test8, form);
+}, "An id shouldn't affect getting an form by name");
+</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-05.html
@@ -0,0 +1,104 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Named items: embeds</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<div id="test">
+<embed name=test1></embed>
+
+<embed name=test2></embed>
+<embed name=test2></embed>
+
+<embed id=test3></embed>
+
+<embed id=test4></embed>
+<embed id=test4></embed>
+
+<embed name=test5></embed>
+<embed id=test5></embed>
+
+<embed id=test6></embed>
+<embed name=test6></embed>
+
+<embed id=test7 name=fail></embed>
+
+<embed name=test8 id=fail></embed>
+</div>
+<script>
+test(function() {
+  var embed = document.getElementsByTagName("embed")[0];
+  assert_equals(embed.name, "test1");
+
+  assert_true("test1" in document, '"test1" in document should be true');
+  assert_equals(document.test1, embed);
+}, "If there is one embed, it should be returned (name)");
+
+test(function() {
+  var embed1 = document.getElementsByTagName("embed")[1];
+  assert_equals(embed1.name, "test2");
+  var embed2 = document.getElementsByTagName("embed")[2];
+  assert_equals(embed2.name, "test2");
+
+  assert_true("test2" in document, '"test2" in document should be true');
+  var collection = document.test2;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [embed1, embed2]);
+}, "If there are two embeds, a collection should be returned. (name)");
+
+test(function() {
+  var embed = document.getElementsByTagName("embed")[3];
+  assert_equals(embed.id, "test3");
+
+  assert_false("test3" in document, '"test3" in document should be false');
+  assert_equals(document.test3, undefined);
+}, "If there is one embed, it should not be returned (id)");
+
+test(function() {
+  var embed1 = document.getElementsByTagName("embed")[4];
+  assert_equals(embed1.id, "test4");
+  var embed2 = document.getElementsByTagName("embed")[5];
+  assert_equals(embed2.id, "test4");
+
+  assert_false("test4" in document, '"test4" in document should be false');
+  assert_equals(document.test4, undefined);
+}, "If there are two embeds, nothing should be returned. (id)");
+
+test(function() {
+  var embed1 = document.getElementsByTagName("embed")[6];
+  assert_equals(embed1.name, "test5");
+  var embed2 = document.getElementsByTagName("embed")[7];
+  assert_equals(embed2.id, "test5");
+
+  assert_true("test5" in document, '"test5" in document should be true');
+  assert_equals(document.test5, embed1);
+}, "If there are two embeds, a collection should be returned. (name and id)");
+
+test(function() {
+  var embed1 = document.getElementsByTagName("embed")[8];
+  assert_equals(embed1.id, "test6");
+  var embed2 = document.getElementsByTagName("embed")[9];
+  assert_equals(embed2.name, "test6");
+
+  assert_true("test6" in document, '"test6" in document should be true');
+  assert_equals(document.test6, embed2);
+}, "If there are two embeds, a collection should be returned. (id and name)");
+
+test(function() {
+  var embed = document.getElementsByTagName("embed")[10];
+  assert_equals(embed.id, "test7");
+
+  assert_false("test7" in document, '"test7" in document should be false');
+  assert_equals(document.test7, undefined);
+}, "A name shouldn't affect getting an embed by id");
+
+test(function() {
+  var embed = document.getElementsByTagName("embed")[11];
+  assert_equals(embed.name, "test8");
+
+  assert_true("test8" in document, '"test8" in document should be true');
+  assert_equals(document.test8, embed);
+}, "An id shouldn't affect getting an embed by name");
+</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/documents/dta/test_nameditem-06.html
@@ -0,0 +1,106 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Named items: imgs</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html/#dom-document-nameditem">
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<div id="test">
+<img name=test1>
+
+<img name=test2>
+<img name=test2>
+
+<img id=test3>
+
+<img id=test4>
+<img id=test4>
+
+<img name=test5>
+<img id=test5>
+
+<img id=test6>
+<img name=test6>
+
+<img id=test7 name=fail>
+
+<img name=test8 id=fail>
+</div>
+<script>
+test(function() {
+  var img = document.getElementsByTagName("img")[0];
+  assert_equals(img.name, "test1");
+
+  assert_true("test1" in document, '"test1" in document should be true');
+  assert_equals(document.test1, img);
+}, "If there is one img, it should be returned (name)");
+
+test(function() {
+  var img1 = document.getElementsByTagName("img")[1];
+  assert_equals(img1.name, "test2");
+  var img2 = document.getElementsByTagName("img")[2];
+  assert_equals(img2.name, "test2");
+
+  assert_true("test2" in document, '"test2" in document should be true');
+  var collection = document.test2;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [img1, img2]);
+}, "If there are two imgs, a collection should be returned. (name)");
+
+test(function() {
+  var img = document.getElementsByTagName("img")[3];
+  assert_equals(img.id, "test3");
+
+  assert_false("test3" in document, '"test3" in document should be false');
+  assert_equals(document.test3, undefined);
+}, "If there is one img, it should not be returned (id)");
+
+test(function() {
+  var img1 = document.getElementsByTagName("img")[4];
+  assert_equals(img1.id, "test4");
+  var img2 = document.getElementsByTagName("img")[5];
+  assert_equals(img2.id, "test4");
+
+  assert_false("test4" in document, '"test4" in document should be false');
+  var collection = document.test4;
+  assert_class_string(collection, "HTMLCollection", "collection should be an HTMLCollection");
+  assert_array_equals(collection, [img1, img2]);
+}, "If there are two imgs, nothing should be returned. (id)");
+
+test(function() {
+  var img1 = document.getElementsByTagName("img")[6];
+  assert_equals(img1.name, "test5");
+  var img2 = document.getElementsByTagName("img")[7];
+  assert_equals(img2.id, "test5");
+
+  assert_true("test5" in document, '"test5" in document should be true');
+  assert_equals(document.test5, img1);
+}, "If there are two imgs, the one with a name should be returned. (name and id)");
+
+test(function() {
+  var img1 = document.getElementsByTagName("img")[8];
+  assert_equals(img1.id, "test6");
+  var img2 = document.getElementsByTagName("img")[9];
+  assert_equals(img2.name, "test6");
+
+  assert_true("test6" in document, '"test6" in document should be true');
+  assert_equals(document.test6, img2);
+}, "If there are two imgs, the one with a name should be returned. (id and name)");
+
+test(function() {
+  var img = document.getElementsByTagName("img")[10];
+  assert_equals(img.id, "test7");
+
+  assert_true("test7" in document, '"test7" in document should be true');
+  assert_equals(document.test7, img);
+}, "A name should affect getting an img by id");
+
+test(function() {
+  var img = document.getElementsByTagName("img")[11];
+  assert_equals(img.name, "test8");
+
+  assert_true("test8" in document, '"test8" in document should be true');
+  assert_equals(document.test8, img);
+}, "An id shouldn't affect getting an img by name");
+</script>
rename from layout/reftests/bidi/dirAuto/dir_auto-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-EN-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-EN-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-EN.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-N-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-N-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-L-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-L-ref.html
@@ -5,22 +5,19 @@
     <title>HTML Test: dir=auto, start with bdi, then L</title>
     <link rel="reference" href="dir_auto-contained-bdi-L-ref.html" />
     <link rel="author" title="Matitiahu Allouche" href="mailto:matitiahu.allouche@google.com" />
     <link rel="author" title="Oren Roth" href="mailto:oren.roth@gmail.com" />
     <link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
     <link rel="help" href="http://dev.w3.org/html5/spec/Overview.html#the-dir-attribute" />
     <meta name="assert" content="
       When dir='auto', the direction is set according to the first strong character
-      of the text.
+      of the text while ignoring bdi elements.
       In this test, it is the Latin letter A, thus the direction must be
-      resolved as LTR.
-      The element with dir='auto' contains a bdi element whose first
-      strong character is RTL. This is ignored by the containing
-      element, but causes the bdi itself to be resolved as RTL" />
+      resolved as LTR." />
     <style>
       input, textarea {
         font-size:1em;
       }
       body {
         font-size:2em;
       }
       .test, .ref {
@@ -41,24 +38,24 @@
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
       &#x05D3; - The Hebrew letter Dalet (strongly RTL).
       &#x05D4; - The Hebrew letter He (strongly RTL).
       &#x05D5; - The Hebrew letter Vav (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-L.html
@@ -5,22 +5,19 @@
     <title>HTML Test: dir=auto, start with bdi, then L</title>
     <link rel="reference" href="dir_auto-contained-bdi-L-ref.html" />
     <link rel="author" title="Matitiahu Allouche" href="mailto:matitiahu.allouche@google.com" />
     <link rel="author" title="Oren Roth" href="mailto:oren.roth@gmail.com" />
     <link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
     <link rel="help" href="http://dev.w3.org/html5/spec/Overview.html#the-dir-attribute" />
     <meta name="assert" content="
       When dir='auto', the direction is set according to the first strong character
-      of the text.
+      of the text while ignoring bdi elements.
       In this test, it is the Latin letter A, thus the direction must be
-      resolved as LTR. 
-      The element with dir='auto' contains a bdi element whose first
-      strong character is RTL. This is ignored by the containing
-      element, but causes the bdi itself to be resolved as RTL." />
+      resolved as LTR." />
     <style>
       input, textarea {
         font-size:1em;
       }
       body {
         font-size:2em;
       }
       .test, .ref {
@@ -41,24 +38,24 @@
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
       &#x05D3; - The Hebrew letter Dalet (strongly RTL).
       &#x05D4; - The Hebrew letter He (strongly RTL).
       &#x05D5; - The Hebrew letter Vav (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="auto"><bdi>123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="auto"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="auto"><bdi>123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="auto"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><bdi dir="rtl">123&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><bdi>&#x05D3;&#x05D4;&#x05D5;</bdi>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-R-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-R-ref.html
@@ -5,22 +5,19 @@
     <title>HTML Test: dir=auto, start with bdi, then R</title>
     <link rel="reference" href="dir_auto-contained-bdi-R-ref.html" />
     <link rel="author" title="Matitiahu Allouche" href="mailto:matitiahu.allouche@google.com" />
     <link rel="author" title="Oren Roth" href="mailto:oren.roth@gmail.com" />
     <link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
     <link rel="help" href="http://dev.w3.org/html5/spec/Overview.html#the-dir-attribute" />
     <meta name="assert" content="
       When dir='auto', the direction is set according to the first strong character
-      of the text.
+      of the text while ignoring bdi elements.
       In this test, it is the Hebrew letter Alef, thus the direction must be
-      resolved as RTL.   
-      The element with dir='auto' contains a bdi element whose first
-      strong character is LTR. This is ignored by the containing
-      element, but causes the bdi itself to be resolved as LTR." />
+      resolved as RTL." />
     <style>
       input, textarea {
         font-size:1em;
       }
       body {
         font-size:2em;
       }
       .test, .ref {
@@ -38,24 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-bdi-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-bdi-R.html
@@ -5,22 +5,19 @@
     <title>HTML Test: dir=auto, start with bdi, then R</title>
     <link rel="reference" href="dir_auto-contained-bdi-R-ref.html" />
     <link rel="author" title="Matitiahu Allouche" href="mailto:matitiahu.allouche@google.com" />
     <link rel="author" title="Oren Roth" href="mailto:oren.roth@gmail.com" />
     <link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
     <link rel="help" href="http://dev.w3.org/html5/spec/Overview.html#the-dir-attribute" />
     <meta name="assert" content="
       When dir='auto', the direction is set according to the first strong character
-      of the text.
+      of the text while ignoring bdi elements.
       In this test, it is the Hebrew letter Alef, thus the direction must be
-      resolved as RTL.  
-      The element with dir='auto' contains a bdi element whose first
-      strong character is LTR. This is ignored by the containing
-      element, but causes the bdi itself to be resolved as LTR." />
+      resolved as RTL." />
     <style>
       input, textarea {
         font-size:1em;
       }
       body {
         font-size:2em;
       }
       .test, .ref {
@@ -38,24 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="auto"><bdi>123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="auto"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="auto"><bdi>123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="auto"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><bdi dir="ltr">123DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><bdi>DEF</bdi>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
   </body>
 </html>
copy from layout/reftests/bidi/dirAuto/dir_auto-contained-dir-L-ref.html
copy to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir-L.html
copy from layout/reftests/bidi/dirAuto/dir_auto-contained-dir-R-ref.html
copy to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir_auto-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir_auto-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir_auto-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-dir_auto-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-dir_auto-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-script-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-script-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-script-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-script-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-script-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-script-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-script-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-script-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-style-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-L-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-style-L-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-L-ref.html
@@ -35,36 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-style-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-style-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-L.html
@@ -35,36 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="auto"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="auto"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="auto"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="auto"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
       <div dir="rtl">
-        <div dir="ltr"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:red;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
+        <div dir="ltr"><style>body {color:black;}</style>ABC&#x05D0;&#x05D1;&#x05D2;.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-style-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-R-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-style-R-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-R-ref.html
@@ -35,36 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-style-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-contained-style-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-style-R.html
@@ -35,36 +35,24 @@
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
     </div>
     <div class="test">
       <div dir="ltr">
-        <div dir="auto"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="auto"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="auto"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="auto"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
     <div class="ref">
       <div dir="ltr">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
       <div dir="rtl">
-        <div dir="rtl"><style>input, textarea {
-        font-size:1em;
-      }
-      body {color:blue;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
+        <div dir="rtl"><style>body {color:black;}</style>&#x05D0;&#x05D1;&#x05D2;ABC.</div>
       </div>
     </div>
   </body>
 </html>
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-textarea-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-textarea-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-textarea-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-contained-textarea-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-contained-textarea-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-EN-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-EN-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-EN.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-L.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-N-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-N-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-R.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-L.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '123ABC\u05D0\u05D1\u05D2.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="&#x05D0;" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-EN-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-EN-R.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '123\u05D0\u05D1\u05D2ABC.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="a" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-L.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = 'ABC\u05D0\u05D1\u05D2.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="&#x05D0;" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-L.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '.-=123ABC\u05D0\u05D1\u05D2.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="&#x05D0;" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-R.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '.-=123\u05D0\u05D1\u05D2ABC.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="a" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-N-EN.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-EN.html
@@ -29,22 +29,28 @@
       }
       .comments {
         display: none;
       }
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
+    <div class="comments">
+      Key to entities used below:
+      &#x05D0; - The Hebrew letter Alef (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
+    </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '@123!';
           }
         };
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="&#x05D0;" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-L-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-L-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-L.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-L.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-N-L.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-L.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '.-=ABC\u05D0\u05D1\u05D2.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="&#x05D0;" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-N-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-N-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-N-R.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '.-=\u05D0\u05D1\u05D2ABC.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="a" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-R-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-R-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-input-script-R.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-R.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-input-script-R.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-input-script-R.html
@@ -33,23 +33,25 @@
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
       &#x05D1; - The Hebrew letter Bet (strongly RTL).
       &#x05D2; - The Hebrew letter Gimel (strongly RTL).
+      This test makes sure that the direction is set correctly for an input whose value is set
+      dynamically by script.
     </div>
       <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var inputs = test.getElementsByTagName('input');
-          for (var i = 0; i < inputs.length; i++) {
+          for (var i = 0; i != inputs.length; i++) {
             inputs[i].value = '\u05D0\u05D1\u05D2ABC.';
           }
         }
       </script>
       <div dir="ltr">
         <input type="text" dir="auto" value="a" />
       </div>
       <div dir="rtl">
rename from layout/reftests/bidi/dirAuto/dir_auto-isolate-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-isolate-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-isolate-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-isolate-ref.html
@@ -30,16 +30,18 @@
       }
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
+      &#x202D; - The LRO (left-to-right override) formatting character.
+      &#x202C; - The PDF (pop directional formatting) formatting character; closes LRO.
     </div>
     <div class="test">
       <div dir="ltr">
         &#x202D;1 a! &#x05D0;&#x202C;
       </div>
       <div dir="rtl">
         &#x202D;a !&#x05D0; 1&#x202C;
       </div>
rename from layout/reftests/bidi/dirAuto/dir_auto-isolate.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-isolate.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-isolate.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-isolate.html
@@ -30,17 +30,17 @@
       }
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
       &#x05D0; - The Hebrew letter Alef (strongly RTL).
-      &#x202D; - The LRO (left-to-right-override) formatting character.
+      &#x202D; - The LRO (left-to-right override) formatting character.
       &#x202C; - The PDF (pop directional formatting) formatting character; closes LRO.
     </div>
     <div class="test">
       <div dir="ltr">
         &#x05D0; <span dir="auto">a!</span> 1
       </div>
       <div dir="rtl">
         a <span dir="auto">&#x05D0;!</span> 1
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-N-EN.html
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-N-between-Rs-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-N-between-Rs-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-N-between-Rs.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-N-between-Rs.html
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-mixed-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-mixed-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-pre-mixed.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-pre-mixed.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-N-EN.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-N-between-Rs-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-N-between-Rs-ref.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-textarea-N-between-Rs-ref.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-N-between-Rs-ref.html
@@ -1,13 +1,12 @@
 <!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
-    <link rel="reference" href="dir_auto-textarea-N-between-Rs-ref.html" />
     <link rel="author" title="Aharon Lanin" href="mailto:aharon@google.com" />
     <link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
     <style>
       body, textarea {
         font-size:18px;
         text-align:left;
       }
       textarea {
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-N-between-Rs.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-N-between-Rs.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-mixed-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-mixed-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-mixed.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-mixed.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-EN-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-EN-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-EN.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-EN.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-EN.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-EN.html
@@ -29,26 +29,28 @@
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
         &#x200E; - LRM, the invisible left-to-right mark (strongly LTR).
         &#x200F; - RLM, the invisible right-to-left mark (strongly RTL).
+      This test makes sure that the direction is set correctly for a textarea whose value is set
+      dynamically by script.
       We use text-align:left because neither the dir="auto" nor the unicode-bidi:plaintext
       specification states whether text-align:start and text-align:end should obey the paragraph
       direction or the direction property in a unicode-bidi:plaintext element.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var textareas = test.getElementsByTagName('textarea');
-          for (var i = 0; i < textareas.length; i++) {
+          for (var i = 0; i != textareas.length; i++) {
             textareas[i].value = '@123!\n';
           }
         }
       </script>
       <div dir="ltr">
         <textarea rows="2" dir="auto">
 &#x200F;
         </textarea>
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-between-Rs-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-between-Rs-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-between-Rs.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-between-Rs.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-textarea-script-N-between-Rs.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-N-between-Rs.html
@@ -31,16 +31,18 @@
       }
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
         &#x05D0; - The Hebrew letter Alef (strongly RTL).
+      This test makes sure that the direction is set correctly for a textarea whose value is set
+      dynamically by script.
       We use text-align:left because neither the dir="auto" nor the unicode-bidi:plaintext
       specification states whether text-align:start and text-align:end should obey the paragraph
       direction or the direction property in a unicode-bidi:plaintext element.
       The ...! paragraph, being neutral, is supposed to be displayed LTR (i.e. as ...!, not as !...)
       despite both the paragraph before it and the paragraph after it being all-RTL, which makes the
       element as a whole RTL.
     </div>
     <div id="test" class="test">
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-mixed-ref.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-mixed-ref.html
rename from layout/reftests/bidi/dirAuto/dir_auto-textarea-script-mixed.html
rename to dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-mixed.html
--- a/layout/reftests/bidi/dirAuto/dir_auto-textarea-script-mixed.html
+++ b/dom/imptests/html/html/dom/elements/global-attributes/dir_auto-textarea-script-mixed.html
@@ -31,26 +31,28 @@
     </style>
   </head>
   <body>
     <div class="instructions"><p>Test passes if the two boxes below look exactly the same.</p></div>
     <div class="comments">
       Key to entities used below:
         &#x200E; - LRM, the invisible left-to-right mark (strongly LTR).
         &#x200F; - RLM, the invisible right-to-left mark (strongly RTL).
+      This test makes sure that the direction is set correctly for a textarea whose value is set
+      dynamically by script.
       We use text-align:left because neither the dir="auto" nor the unicode-bidi:plaintext
       specification states whether text-align:start and text-align:end should obey the paragraph
       direction or the direction property in a unicode-bidi:plaintext element.
     </div>
     <div id="test" class="test">
       <script>
         window.onload = function() {
           var test = document.getElementById('test');
           var textareas = test.getElementsByTagName('textarea');
-          for (var i = 0; i < textareas.length; i++) {
+          for (var i = 0; i != textareas.length; i++) {
             var input = textareas[i];
             if (input.parentNode.dir == 'ltr') {
               // Assign a value whose first strong is RTL.
               input.value =
                   '!\u200F123\u200E@\n' +
                   '@\u200E123\u200F!\n' +
                   '!123\u200F\u200E@\n' +
                   '@123\u200E\u200F!\n';
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/lang-xmllang-01-ref.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<title>Languages</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html5/#the-lang-and-xml:lang-attributes">
+<link tel="help" href="http://www.w3.org/TR/CSS2/selector.html#lang">
+<meta name="flags" content="css21">
+<style>
+#test > * { background: limegreen; }
+</style>
+<body>
+<p>All lines below should have a green background.</p>
+<div id="test">
+<div><p>{}{lang}{en}</p></div>
+<div><p>{}{xml:lang}{en}</p></div>
+<div><div><p>Parent: {}{lang}{en}</p></div></div>
+<div><div><p>Parent: {}{xml:lang}{en}</p></div></div>
+<div><p>{xml}{lang}{en}</p></div>
+<div><p>{xml}{lang}{en} - {lang}{de}</p></div>
+<div><p>{xml}{lang}{de} - {lang}{en}</p></div>
+</div>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/lang-xmllang-01.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<title>Languages</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html5/#the-lang-and-xml:lang-attributes">
+<link tel="help" href="http://www.w3.org/TR/CSS2/selector.html#lang">
+<meta name="flags" content="css21">
+<style>
+#test #a :lang(en) { background: limegreen; }
+#test #b :lang(nl) { background: limegreen; }
+#test #c :lang(en) { background: limegreen; }
+#test #d :lang(nl) { background: limegreen; }
+#test #e :lang(en) { background: limegreen; }
+#test #f :lang(en) { background: limegreen; }
+#test #g :lang(de) { background: limegreen; }
+</style>
+<body>
+<p>All lines below should have a green background.</p>
+<div id="test" lang="nl">
+<div id="a"><p lang="en">{}{lang}{en}</p></div>
+<div id="b"><p xml:lang="en">{}{xml:lang}{en}</p></div>
+<div id="c"><div lang="en"><p>Parent: {}{lang}{en}</p></div></div>
+<div id="d"><div xml:lang="en"><p>Parent: {}{xml:lang}{en}</p></div></div>
+</div>
+<script>
+try {
+  var XML = "http://www.w3.org/XML/1998/namespace";
+  var container = document.getElementById("test");
+
+  var div = document.createElement("div");
+  div.id = "e";
+  var testNode = document.createElement("p");
+  testNode.appendChild(document.createTextNode("{xml}{lang}{en}"));
+  testNode.setAttributeNS(XML, "xml:lang", "en");
+  div.appendChild(testNode);
+  container.appendChild(div);
+
+  div = document.createElement("div");
+  div.id = "f";
+  testNode = document.createElement("p");
+  testNode.appendChild(document.createTextNode("{xml}{lang}{en} - {lang}{de}"));
+  testNode.setAttributeNS(XML, "xml:lang", "en");
+  testNode.setAttributeNS(null, "lang", "de");
+  div.appendChild(testNode);
+  container.appendChild(div);
+
+  div = document.createElement("div");
+  div.id = "g";
+  testNode = document.createElement("p");
+  testNode.appendChild(document.createTextNode("{xml}{lang}{de} - {lang}{en}"));
+  testNode.setAttributeNS(XML, "xml:lang", "de");
+  testNode.setAttributeNS(null, "lang", "en");
+  container.appendChild(testNode);
+  div.appendChild(testNode);
+  container.appendChild(div);
+} catch (e) {
+}
+</script>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/lang-xyzzy-ref.html
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<title>Invalid languages</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<meta name="flags" content="css21">
+<style>#testp { color: green; }</style>
+<body>
+<div id="test">
+<p id="testp" lang="xyzzy">ABC</p>
+</div>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/lang-xyzzy.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<title>Invalid languages</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html5/#the-lang-and-xml:lang-attributes">
+<link tel="help" href="http://www.w3.org/TR/CSS2/selector.html#lang">
+<meta name="flags" content="css21">
+<style>:lang(xyzzy) { color: green; }</style>
+<body>
+<div id="test">
+<p id="testp" lang="xyzzy">ABC</p>
+</div>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/reftest.list
@@ -0,0 +1,56 @@
+# THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
+
+== dir_auto-contained-bdi-L.html dir_auto-contained-bdi-L-ref.html
+== dir_auto-contained-bdi-R.html dir_auto-contained-bdi-R-ref.html
+== dir_auto-contained-dir_auto-L.html dir_auto-contained-dir_auto-L-ref.html
+== dir_auto-contained-dir_auto-R.html dir_auto-contained-dir_auto-R-ref.html
+== dir_auto-contained-dir-L.html dir_auto-contained-dir-L-ref.html
+== dir_auto-contained-dir-R.html dir_auto-contained-dir-R-ref.html
+== dir_auto-contained-L.html dir_auto-contained-L-ref.html
+== dir_auto-contained-R.html dir_auto-contained-R-ref.html
+== dir_auto-contained-script-L.html dir_auto-contained-script-L-ref.html
+== dir_auto-contained-script-R.html dir_auto-contained-script-R-ref.html
+== dir_auto-contained-style-L.html dir_auto-contained-style-L-ref.html
+== dir_auto-contained-style-R.html dir_auto-contained-style-R-ref.html
+== dir_auto-contained-textarea-L.html dir_auto-contained-textarea-L-ref.html
+== dir_auto-contained-textarea-R.html dir_auto-contained-textarea-R-ref.html
+== dir_auto-EN-L.html dir_auto-EN-L-ref.html
+== dir_auto-EN-R.html dir_auto-EN-R-ref.html
+== dir_auto-input-EN-L.html dir_auto-input-EN-L-ref.html
+== dir_auto-input-EN-R.html dir_auto-input-EN-R-ref.html
+== dir_auto-input-L.html dir_auto-input-L-ref.html
+== dir_auto-input-N-EN.html dir_auto-input-N-EN-ref.html
+== dir_auto-input-N-EN-L.html dir_auto-input-N-EN-L-ref.html
+== dir_auto-input-N-EN-R.html dir_auto-input-N-EN-R-ref.html
+== dir_auto-input-N-L.html dir_auto-input-N-L-ref.html
+== dir_auto-input-N-R.html dir_auto-input-N-R-ref.html
+== dir_auto-input-R.html dir_auto-input-R-ref.html
+== dir_auto-input-script-EN-L.html dir_auto-input-script-EN-L-ref.html
+== dir_auto-input-script-EN-R.html dir_auto-input-script-EN-R-ref.html
+== dir_auto-input-script-L.html dir_auto-input-script-L-ref.html
+== dir_auto-input-script-N-EN.html dir_auto-input-script-N-EN-ref.html
+== dir_auto-input-script-N-EN-L.html dir_auto-input-script-N-EN-L-ref.html
+== dir_auto-input-script-N-EN-R.html dir_auto-input-script-N-EN-R-ref.html
+== dir_auto-input-script-N-L.html dir_auto-input-script-N-L-ref.html
+== dir_auto-input-script-N-R.html dir_auto-input-script-N-R-ref.html
+== dir_auto-input-script-R.html dir_auto-input-script-R-ref.html
+== dir_auto-isolate.html dir_auto-isolate-ref.html
+== dir_auto-L.html dir_auto-L-ref.html
+== dir_auto-N-EN.html dir_auto-N-EN-ref.html
+== dir_auto-N-EN-L.html dir_auto-N-EN-L-ref.html
+== dir_auto-N-EN-R.html dir_auto-N-EN-R-ref.html
+== dir_auto-N-L.html dir_auto-N-L-ref.html
+== dir_auto-N-R.html dir_auto-N-R-ref.html
+== dir_auto-pre-mixed.html dir_auto-pre-mixed-ref.html
+== dir_auto-pre-N-between-Rs.html dir_auto-pre-N-between-Rs-ref.html
+== dir_auto-pre-N-EN.html dir_auto-pre-N-EN-ref.html
+== dir_auto-R.html dir_auto-R-ref.html
+== dir_auto-textarea-mixed.html dir_auto-textarea-mixed-ref.html
+== dir_auto-textarea-N-between-Rs.html dir_auto-textarea-N-between-Rs-ref.html
+== dir_auto-textarea-N-EN.html dir_auto-textarea-N-EN-ref.html
+== dir_auto-textarea-script-mixed.html dir_auto-textarea-script-mixed-ref.html
+== dir_auto-textarea-script-N-between-Rs.html dir_auto-textarea-script-N-between-Rs-ref.html
+== dir_auto-textarea-script-N-EN.html dir_auto-textarea-script-N-EN-ref.html
+== lang-xyzzy.html lang-xyzzy-ref.html
+== lang-xmllang-01.html lang-xmllang-01-ref.html
+== style-01.html style-01-ref.html
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/style-01-ref.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<title>The style attribute</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html5/#the-style-attribute">
+<link rel="help" href="http://www.w3.org/TR/css-style-attr/#syntax">
+<link rel="help" href="http://www.w3.org/TR/CSS21/cascade.html#cascading-order">
+<link rel="help" href="http://www.w3.org/TR/CSS21/cascade.html#specificity">
+<style>
+#test p { background: limegreen; }
+</style>
+<div id="test">
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+<p>This line should have a green background.
+</div>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/dom/elements/global-attributes/style-01.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<title>The style attribute</title>
+<link rel="author" title="Ms2ger" href="mailto:ms2ger@gmail.com">
+<link rel="help" href="http://www.whatwg.org/html5/#the-style-attribute">
+<link rel="help" href="http://www.w3.org/TR/css-style-attr/#syntax">
+<link rel="help" href="http://www.w3.org/TR/CSS21/cascade.html#cascading-order">
+<link rel="help" href="http://www.w3.org/TR/CSS21/cascade.html#specificity">
+<style>
+#idsel { background: red; }
+#idsel2 { background: limegreen !important; }
+</style>
+<div id="test">
+<p style="background:limegreen">This line should have a green background.
+<p style="/**/background:limegreen">This line should have a green background.
+<p style="background/**/:limegreen">This line should have a green background.
+<p style="background:/**/limegreen">This line should have a green background.
+<p style="background:limegreen/**/">This line should have a green background.
+<p id="idsel1" style="background:limegreen">This line should have a green background.
+<p id="idsel2" style="background:red">This line should have a green background.
+<p style="background:limegreen; background:r/**/ed">This line should have a green background.
+<p style="background:limegreen;}">This line should have a green background.
+<p style="};background:limegreen">This line should have a green background.
+<p style="background:red;};background:limegreen">This line should have a green background.
+<p style="background:limegreen;{background:red}">This line should have a green background.
+</div>
rename from content/html/content/reftests/hidden-1-ref.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1-ref.html
--- a/content/html/content/reftests/hidden-1-ref.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1-ref.html
@@ -1,5 +1,4 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
 <p>This line should be visible.
rename from content/html/content/reftests/hidden-1a.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1a.html
--- a/content/html/content/reftests/hidden-1a.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1a.html
@@ -1,6 +1,7 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <p>This line should be visible.
 <p hidden>This line should not be visible.
rename from content/html/content/reftests/hidden-1b.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1b.html
--- a/content/html/content/reftests/hidden-1b.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1b.html
@@ -1,9 +1,10 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <style>
 p { display: none; }
 [hidden] { display: block; }
 </style>
 <p hidden>This line should be visible.
rename from content/html/content/reftests/hidden-1c.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1c.html
--- a/content/html/content/reftests/hidden-1c.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1c.html
@@ -1,10 +1,11 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <p hidden>This line should be visible.
 <p>This line should not be visible.
 <script>
 document.getElementsByTagName("p")[0].hidden = false;
 document.getElementsByTagName("p")[1].hidden = true;
 </script>
rename from content/html/content/reftests/hidden-1d.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1d.html
--- a/content/html/content/reftests/hidden-1d.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1d.html
@@ -1,10 +1,11 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <p hidden>This line should be visible.
 <p>This line should not be visible.
 <script>
 document.getElementsByTagName("p")[0].removeAttribute("hidden");
 document.getElementsByTagName("p")[1].setAttribute("hidden", "");
 </script>
rename from content/html/content/reftests/hidden-1e.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1e.html
--- a/content/html/content/reftests/hidden-1e.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1e.html
@@ -1,8 +1,9 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <style>
 p { display: block; }
 </style>
 <p hidden>This line should be visible.
rename from content/html/content/reftests/hidden-1f.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1f.html
--- a/content/html/content/reftests/hidden-1f.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1f.html
@@ -1,8 +1,9 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <style>
 p { display: block !important; }
 </style>
 <p hidden>This line should be visible.
rename from content/html/content/reftests/hidden-1g.html
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-1g.html
--- a/content/html/content/reftests/hidden-1g.html
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-1g.html
@@ -1,9 +1,10 @@
 <!doctype html>
 <title>The hidden attribute</title>
-<link rel=author title=Ms2ger href=ms2ger@gmail.com>
-<link rel=help href=http://www.whatwg.org/html5/#the-hidden-attribute>
+<link rel=author title=Ms2ger href=mailto:Ms2ger@gmail.com>
+<link rel=help href=http://www.whatwg.org/html/#the-hidden-attribute>
+<link rel=help href=http://www.whatwg.org/html/#hidden-elements>
 <p>This line should be visible.
 <p hidden=hidden>This line should not be visible.
 <p hidden=blue>This line should not be visible.
 <p hidden=true>This line should not be visible.
 <p hidden=false>This line should not be visible.
rename from content/html/content/reftests/hidden-2-ref.svg
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-2-ref.svg
--- a/content/html/content/reftests/hidden-2-ref.svg
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-2-ref.svg
@@ -1,9 +1,7 @@
 <svg xmlns="http://www.w3.org/2000/svg" height="20" width="20">
 <metadata>
   <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Ms2ger"
-        href="ms2ger@gmail.com"/>
-  <link xmlns="http://www.w3.org/1999/xhtml" rel="help"
-        href="http://www.whatwg.org/html5/#the-hidden-attribute"/>
+        href="mailto:Ms2ger@gmail.com"/>
 </metadata>
 <rect height="20" width="20"/>
 </svg>
rename from content/html/content/reftests/hidden-2.svg
rename to dom/imptests/html/html/editing/the-hidden-attribute/hidden-2.svg
--- a/content/html/content/reftests/hidden-2.svg
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/hidden-2.svg
@@ -1,9 +1,11 @@
 <svg xmlns="http://www.w3.org/2000/svg" height="20" width="20">
 <metadata>
   <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Ms2ger"
-        href="ms2ger@gmail.com"/>
+        href="mailto:Ms2ger@gmail.com"/>
   <link xmlns="http://www.w3.org/1999/xhtml" rel="help"
-        href="http://www.whatwg.org/html5/#the-hidden-attribute"/>
+        href="http://www.whatwg.org/html/#the-hidden-attribute"/>
+  <link xmlns="http://www.w3.org/1999/xhtml" rel="help"
+        href="http://www.whatwg.org/html/#hidden-elements"/>
 </metadata>
 <rect hidden="" height="20" width="20"/>
 </svg>
new file mode 100644
--- /dev/null
+++ b/dom/imptests/html/html/editing/the-hidden-attribute/reftest.list
@@ -0,0 +1,10 @@
+# THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
+
+== hidden-1a.html hidden-1-ref.html
+== hidden-1b.html hidden-1-ref.html
+== hidden-1c.html hidden-1-ref.html
+== hidden-1d.html hidden-1-ref.html
+== hidden-1e.html hidden-1-ref.html
+== hidden-1f.html hidden-1-ref.html
+== hidden-1g.html hidden-1-ref.html
+== hidden-2.svg hidden-2-ref.svg
--- a/dom/imptests/html/html/semantics/scripting-1/the-script-element/moz.build
+++ b/dom/imptests/html/html/semantics/scripting-1/the-script-element/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/html/html/webappapis/scripting/events/moz.build
+++ b/dom/imptests/html/html/webappapis/scripting/events/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/html/html/webappapis/scripting/processing-model-2/moz.build
+++ b/dom/imptests/html/html/webappapis/scripting/processing-model-2/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/html/old-tests/submission/Opera/microdata/moz.build
+++ b/dom/imptests/html/old-tests/submission/Opera/microdata/moz.build
@@ -1,5 +1,4 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # THIS FILE IS AUTOGENERATED BY importTestsuite.py - DO NOT EDIT
 
 DIRS += [
 ]
--- a/dom/imptests/importTestsuite.py
+++ b/dom/imptests/importTestsuite.py
@@ -15,158 +15,188 @@ from __future__ import print_function, u
 import os
 import shutil
 import subprocess
 import sys
 
 import parseManifest
 import writeBuildFiles
 
-HEADERS_SUFFIX = "^headers^"
+def readManifests(iden, dirs):
+    def parseManifestFile(iden, path):
+        pathstr = "hg-%s/%s/MANIFEST" % (iden, path)
+        subdirs, mochitests, reftests, _, supportfiles = parseManifest.parseManifestFile(pathstr)
+        return subdirs, mochitests, reftests, supportfiles
 
-def parseManifestFile(dest, dir):
-    subdirs, mochitests, _, __, supportfiles = parseManifest.parseManifestFile("hg-%s/%s/MANIFEST" % (dest, dir))
-    return subdirs, mochitests, supportfiles
+    data = []
+    for path in dirs:
+        subdirs, mochitests, reftests, supportfiles = parseManifestFile(iden, path)
+        data.append({
+          "path": path,
+          "mochitests": mochitests,
+          "reftests": reftests,
+          "supportfiles": supportfiles,
+        })
+        data.extend(readManifests(iden, ["%s/%s" % (path, d) for d in subdirs]))
+    return data
+
 
 def getData(confFile):
     """This function parses a file of the form
-    URL of remote repository|Name of the destination directory
+    (hg or git)|URL of remote repository|identifier for the local directory
     First directory of tests
     ...
     Last directory of tests"""
-    repo = ""
-    dest = ""
+    vcs = ""
+    url = ""
+    iden = ""
     directories = []
     try:
         with open(confFile, 'r') as fp:
             first = True
             for line in fp:
                 if first:
-                    idx = line.index("|")
-                    repo = line[:idx].strip()
-                    dest = line[idx + 1:].strip()
+                    vcs, url, iden = line.strip().split("|")
                     first = False
                 else:
                     directories.append(line.strip())
     finally:
-        return repo, dest, directories
+        return vcs, url, iden, directories
 
-def makePath(a, b):
+
+def makePathInternal(a, b):
     if not b:
         # Empty directory, i.e., the repository root.
         return a
     return "%s/%s" % (a, b)
 
-def shorten(path):
-    path = path.replace('dom-tree-accessors', 'dta')
-    path = path.replace('document.getElementsByName', 'doc.gEBN')
-    path = path.replace('requirements-for-implementations', 'implreq')
-    path = path.replace('other-elements-attributes-and-apis', 'oeaaa')
-    return path
+
+def makeSourcePath(a, b):
+    """Make a path in the source (upstream) directory."""
+    return makePathInternal("hg-%s" % a, b)
+
 
-def copyTest(source, dest):
-    """Copy the file at source to dest, as well as any ^headers^ file associated
-    with it."""
-    dest = shorten(dest)
-    shutil.copy(source, dest)
-    if os.path.exists(source + HEADERS_SUFFIX):
-        shutil.copy(source + HEADERS_SUFFIX, dest + HEADERS_SUFFIX)
+def makeDestPath(a, b):
+    """Make a path in the destination (mozilla-central) directory, shortening as
+    appropriate."""
+    def shorten(path):
+        path = path.replace('dom-tree-accessors', 'dta')
+        path = path.replace('document.getElementsByName', 'doc.gEBN')
+        path = path.replace('requirements-for-implementations', 'implreq')
+        path = path.replace('other-elements-attributes-and-apis', 'oeaaa')
+        return path
 
-def copy(thissrcdir, dest, directories):
+    return shorten(makePathInternal(a, b))
+
+
+def extractReftestFiles(reftests):
+    """Returns the set of files referenced in the reftests argument"""
+    files = set()
+    for line in reftests:
+        files.update([line[1], line[2]])
+    return files
+
+
+def copy(dest, directories):
     """Copy mochitests and support files from the external HG directory to their
     place in mozilla-central.
     """
-    print("Copying %s..." % directories)
+    print("Copying tests...")
     for d in directories:
-        subdirs, mochitests, supportfiles = parseManifestFile(dest, d)
-        sourcedir = makePath("hg-%s" % dest, d)
-        destdir = makePath(dest, d)
+        sourcedir = makeSourcePath(dest, d["path"])
+        destdir = makeDestPath(dest, d["path"])
         os.makedirs(destdir)
 
-        for mochitest in mochitests:
-            copyTest("%s/%s" % (sourcedir, mochitest), "%s/test_%s" % (destdir, mochitest))
-        for support in supportfiles:
-            copyTest("%s/%s" % (sourcedir, support), "%s/%s" % (destdir, support))
+        reftestfiles = extractReftestFiles(d["reftests"])
 
-        if len(subdirs):
-            if d:
-                importDirs(thissrcdir, dest, ["%s/%s" % (d, subdir) for subdir in subdirs])
-            else:
-                # Empty directory, i.e., the repository root
-                importDirs(thissrcdir, dest, subdirs)
+        for mochitest in d["mochitests"]:
+            shutil.copy("%s/%s" % (sourcedir, mochitest), "%s/test_%s" % (destdir, mochitest))
+        for reftest in sorted(reftestfiles):
+            shutil.copy("%s/%s" % (sourcedir, reftest), "%s/%s" % (destdir, reftest))
+        for support in d["supportfiles"]:
+            shutil.copy("%s/%s" % (sourcedir, support), "%s/%s" % (destdir, support))
 
 def printMozbuildFile(dest, directories):
     """Create a .mozbuild file to be included into the main moz.build, which
     lists the directories with tests.
     """
     print("Creating mozbuild...")
     path = dest + ".mozbuild"
     with open(path, 'w') as fh:
-        normalized = [makePath(dest, d) for d in directories]
+        normalized = [makeDestPath(dest, d["path"]) for d in directories]
         result = writeBuildFiles.substMozbuild("importTestsuite.py",
             normalized)
         fh.write(result)
 
     subprocess.check_call(["hg", "add", path])
 
-def printBuildFiles(thissrcdir, dest, directories):
+def printBuildFiles(dest, directories):
     """Create Makefile.in files for each directory that contains tests we import.
     """
     print("Creating build files...")
     for d in directories:
-        path = makePath(dest, d)
-        print("Creating Makefile.in in %s..." % path)
+        path = makeDestPath(dest, d["path"])
 
-        subdirs, mochitests, supportfiles = parseManifestFile(dest, d)
-
-        files = ["test_%s" % (mochitest, ) for mochitest in mochitests]
-        files.extend(supportfiles)
-        files.extend(f for f in os.listdir(path) if f.endswith(HEADERS_SUFFIX))
+        files = ["test_%s" % (mochitest, ) for mochitest in d["mochitests"]]
+        files.extend(d["supportfiles"])
 
         with open(path + "/Makefile.in", "w") as fh:
             result = writeBuildFiles.substMakefile("importTestsuite.py", files)
             fh.write(result)
 
-        print("Creating moz.build in %s..." % path)
         with open(path + "/moz.build", "w") as fh:
-            result = writeBuildFiles.substMozbuild("importTestsuite.py",
-                subdirs)
+            result = writeBuildFiles.substMozbuild("importTestsuite.py", [])
             fh.write(result)
 
+        if d["reftests"]:
+            with open(path + "/reftest.list", "w") as fh:
+                result = writeBuildFiles.substReftestList("importTestsuite.py",
+                    d["reftests"])
+                fh.write(result)
+
 
 def hgadd(dest, directories):
     """Inform hg of the files in |directories|."""
     print("hg addremoving...")
     for d in directories:
-        subprocess.check_call(["hg", "addremove", "%s/%s" % (dest, d)])
+        subprocess.check_call(["hg", "addremove", makeDestPath(dest, d)])
 
-def importDirs(thissrcdir, dest, directories):
-    copy(thissrcdir, dest, directories)
-    printBuildFiles(thissrcdir, dest, directories)
+def removeAndCloneRepo(vcs, url, dest):
+    """Replaces the repo at dest by a fresh clone from url using vcs"""
+    assert vcs in ('hg', 'git')
+
+    print("Removing %s..." % dest)
+    subprocess.check_call(["rm", "-rf", dest])
 
-def importRepo(confFile, thissrcdir):
+    print("Cloning %s to %s with %s..." % (url, dest, vcs))
+    subprocess.check_call([vcs, "clone", url, dest])
+
+def importRepo(confFile):
     try:
-        repo, dest, directories = getData(confFile)
-        hgdest = "hg-%s" % (dest, )
-        print("Going to clone %s to %s..." % (repo, hgdest))
+        vcs, url, iden, directories = getData(confFile)
+        dest = iden
+        hgdest = "hg-%s" % iden
+
         print("Removing %s..." % dest)
         subprocess.check_call(["rm", "-rf", dest])
-        print("Removing %s..." % hgdest)
-        subprocess.check_call(["rm", "-rf", hgdest])
-        print("Cloning %s to %s..." % (repo, hgdest))
-        subprocess.check_call(["hg", "clone", repo, hgdest])
-        print("Going to import %s..." % directories)
-        importDirs(thissrcdir, dest, directories)
-        printMozbuildFile(dest, directories)
+
+        removeAndCloneRepo(vcs, url, hgdest)
+
+        data = readManifests(iden, directories)
+        print("Going to import %s..." % [d["path"] for d in data])
+
+        copy(dest, data)
+        printBuildFiles(dest, data)
+        printMozbuildFile(dest, data)
         hgadd(dest, directories)
         print("Removing %s again..." % hgdest)
         subprocess.check_call(["rm", "-rf", hgdest])
     except subprocess.CalledProcessError as e:
         print(e.returncode)
     finally:
         print("Done")
 
 if __name__ == "__main__":
     if len(sys.argv) != 2:
         print("Need one argument.")
     else:
-        importRepo(sys.argv[1], "dom/imptests")
+        importRepo(sys.argv[1])
 
--- a/dom/imptests/moz.build
+++ b/dom/imptests/moz.build
@@ -3,16 +3,17 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += [
     'failures/editing/conformancetest',
     'failures/editing/selecttest',
     'failures/html/html/browsers/the-window-object',
+    'failures/html/html/browsers/the-window-object/named-access-on-the-window-object',
     'failures/html/html/dom/documents/dta',
     'failures/html/html/dom/documents/dta/doc.gEBN',
     'failures/html/html/dom/elements/global-attributes',
     'failures/html/html/obsolete/implreq/oeaaa',
     'failures/html/html/semantics/forms/the-form-element',
     'failures/html/html/semantics/forms/the-option-element',
     'failures/html/html/semantics/forms/the-select-element',
     'failures/html/html/semantics/scripting-1/the-script-element',
new file mode 100644
--- /dev/null
+++ b/dom/imptests/reftest.list
@@ -0,0 +1,2 @@
+include html/html/dom/elements/global-attributes/reftest.list
+include html/html/editing/the-hidden-attribute/reftest.list
--- a/dom/imptests/testharnessreport.js
+++ b/dom/imptests/testharnessreport.js
@@ -1,11 +1,11 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var W3CTest = {
   /**
    * Dictionary mapping a test URL to either the string "all", which means that
    * all tests in this file are expected to fail, or a dictionary mapping test
    * names to either the boolean |true|, or the string "debug". The former
    * means that this test is expected to fail in all builds, and the latter
    * that it is only expected to fail in debug builds.
@@ -45,38 +45,118 @@ var W3CTest = {
    * int(result).
    */
   "prefixes": [
     ["TEST-UNEXPECTED-FAIL", "TEST-PASS"],
     ["TEST-KNOWN-FAIL", "TEST-UNEXPECTED-PASS"]
   ],
 
   /**
+   * Prefix of the path to parent of the the failures directory.
+   */
+  "pathprefix": "/tests/dom/imptests/",
+
+  /**
    * Returns the URL of the current test, relative to the root W3C tests
    * directory. Used as a key into the expectedFailures dictionary.
    */
+  "getPath": function() {
+    var url = this.getURL();
+    if (!url.startsWith(this.pathprefix)) {
+      return "";
+    }
+    return url.substring(this.pathprefix.length);
+  },
+
+  /**
+   * Returns the root-relative URL of the current test.
+   */
   "getURL": function() {
-    return this.runner.currentTestURL.substring("/tests/dom/imptests/".length);
+    return this.runner ? this.runner.currentTestURL : location.pathname;
+  },
+
+  /**
+   * Report the results in the tests array.
+   */
+  "reportResults": function() {
+    var element = function element(aLocalName) {
+      var xhtmlNS = "http://www.w3.org/1999/xhtml";
+      return document.createElementNS(xhtmlNS, aLocalName);
+    };
+
+    var stylesheet = element("link");
+    stylesheet.setAttribute("rel", "stylesheet");
+    stylesheet.setAttribute("href", "/resources/testharness.css");
+    var heads = document.getElementsByTagName("head");
+    if (heads.length) {
+      heads[0].appendChild(stylesheet);
+    }
+
+    var log = document.getElementById("log");
+    if (!log) {
+      return;
+    }
+    var section = log.appendChild(element("section"));
+    section.id = "summary";
+    section.appendChild(element("h2")).textContent = "Details";
+
+    var table = section.appendChild(element("table"));
+    table.id = "results";
+
+    var tr = table.appendChild(element("thead")).appendChild(element("tr"));
+    for (var header of ["Result", "Test Name", "Message"]) {
+      tr.appendChild(element("th")).textContent = header;
+    }
+    var statuses = [
+      ["Unexpected Fail", "Pass"],
+      ["Known Fail", "Unexpected Pass"]
+    ];
+    var tbody = table.appendChild(element("tbody"));
+    for (var test of this.tests) {
+      tr = tbody.appendChild(element("tr"));
+      tr.className = (test.result === !test.todo ? "pass" : "fail");
+      tr.appendChild(element("td")).textContent =
+        statuses[+test.todo][+test.result];
+      tr.appendChild(element("td")).textContent = test.name;
+      tr.appendChild(element("td")).textContent = test.message;
+    }
+  },
+
+  /**
+   * Returns a printable message based on aTest's 'name' and 'message'
+   * properties.
+   */
+  "formatTestMessage": function(aTest) {
+    return aTest.name + (aTest.message ? ": " + aTest.message : "");
   },
 
   /**
    * Lets the test runner know about a test result.
    */
   "_log": function(test) {
+    var url = this.getURL();
     var msg = this.prefixes[+test.todo][+test.result] + " | ";
-    if (this.runner.currentTestURL) {
-      msg += this.runner.currentTestURL;
+    if (url) {
+      msg += url;
     }
-    msg += " | " + test.message;
-    this.runner[(test.result === !test.todo) ? "log" : "error"](msg);
+    msg += " | " + this.formatTestMessage(test);
+    if (this.runner) {
+      this.runner[(test.result === !test.todo) ? "log" : "error"](msg);
+    } else {
+      dump(msg + "\n");
+    }
   },
 
+  /**
+   * Logs a message about collapsed messages (if any), and resets the counter.
+   */
   "_logCollapsedMessages": function() {
     if (this.collapsedMessages) {
       this._log({
+        "name": document.title,
         "result": true,
         "todo": false,
         "message": "Elided " + this.collapsedMessages + " passes or known failures."
       });
     }
     this.collapsedMessages = 0;
   },
 
@@ -117,89 +197,103 @@ var W3CTest = {
     return value === true || (value === "debug" && !!SpecialPowers.isDebugBuild);
   },
 
   /**
    * Callback function for testharness.js. Called when one test in a file
    * finishes.
    */
   "result": function(test) {
-    var url = this.getURL();
+    var url = this.getPath();
     this.report({
-      "message": test.name + (test.message ? "; " + test.message : ""),
+      "name": test.name,
+      "message": test.message || "",
       "result": test.status === test.PASS,
       "todo": this._todo(test)
     });
     if (this.dumpFailures && test.status !== test.PASS) {
       this.failures[test.name] = true;
     }
   },
 
   /**
    * Callback function for testharness.js. Called when the entire test file
    * finishes.
    */
   "finish": function(tests, status) {
-    var url = this.getURL();
+    var url = this.getPath();
     this.report({
-      "message": "Finished test, status " + status.status,
+      "name": "Finished test",
+      "message": "Status: " + status.status,
       "result": status.status === status.OK,
       "todo":
         url in this.expectedFailures &&
         this.expectedFailures[url] === "error"
     });
 
     this._logCollapsedMessages();
 
     if (this.dumpFailures) {
       dump("@@@ @@@ Failures\n");
       dump(url + "@@@" + JSON.stringify(this.failures) + "\n");
     }
-    this.runner.testFinished(this.tests);
+    if (this.runner) {
+      this.runner.testFinished(this.tests.map(function(aTest) {
+        return {
+          "message": this.formatTestMessage(aTest),
+          "result": aTest.result,
+          "todo": aTest.todo
+        };
+      }, this));
+    } else {
+      this.reportResults();
+    }
   },
 
   /**
    * Log an unexpected failure. Intended to be used from harness code, not
    * from tests.
    */
-  "logFailure": function(message) {
+  "logFailure": function(aTestName, aMessage) {
     this.report({
-      "message": message,
+      "name": aTestName,
+      "message": aMessage,
       "result": false,
       "todo": false
     });
   },
 
   /**
    * Timeout the current test. Intended to be used from harness code, not
    * from tests.
    */
   "timeout": function() {
-    this.logFailure("Test runner timed us out.");
+    this.logFailure("Timeout", "Test runner timed us out.");
     timeout();
   }
 };
 (function() {
   try {
-    if (!W3CTest.runner) {
-      return;
-    }
-    // Get expected fails.  If there aren't any, there will be a 404, which is
-    // fine.  Anything else is unexpected.
-    var request = new XMLHttpRequest();
-    request.open("GET", "/tests/dom/imptests/failures/" + W3CTest.getURL() + ".json", false);
-    request.send();
-    if (request.status === 200) {
-      W3CTest.expectedFailures = JSON.parse(request.responseText);
-    } else if (request.status !== 404) {
-      W3CTest.logFailure("Request status was " + request.status);
+    var path = W3CTest.getPath();
+    if (path) {
+      // Get expected fails.  If there aren't any, there will be a 404, which is
+      // fine.  Anything else is unexpected.
+      var url = W3CTest.pathprefix + "failures/" + path + ".json";
+      var request = new XMLHttpRequest();
+      request.open("GET", url, false);
+      request.send();
+      if (request.status === 200) {
+        W3CTest.expectedFailures = JSON.parse(request.responseText);
+      } else if (request.status !== 404) {
+        W3CTest.logFailure("Fetching failures file", "Request status was " + request.status);
+      }
     }
 
     add_result_callback(W3CTest.result.bind(W3CTest));
     add_completion_callback(W3CTest.finish.bind(W3CTest));
     setup({
       "output": false,
       "explicit_timeout": true
     });
   } catch (e) {
-    W3CTest.logFailure("Unexpected exception: " + e);
+    W3CTest.logFailure("Harness setup", "Unexpected exception: " + e);
   }
 })();
--- a/dom/imptests/webapps.txt
+++ b/dom/imptests/webapps.txt
@@ -1,6 +1,6 @@
-https://dvcs.w3.org/hg/webapps|webapps
+hg|https://dvcs.w3.org/hg/webapps|webapps
 DOMCore/tests/approved
 DOMCore/tests/submissions/Ms2ger
 DOMCore/tests/submissions/Opera
 WebStorage/tests/submissions
 XMLHttpRequest/tests/submissions/Ms2ger
--- a/dom/imptests/writeBuildFiles.py
+++ b/dom/imptests/writeBuildFiles.py
@@ -22,16 +22,21 @@ include $$(DEPTH)/config/autoconf.mk
 include $$(topsrcdir)/config/rules.mk
 """
 
 mozbuild_template = """# THIS FILE IS AUTOGENERATED BY ${caller} - DO NOT EDIT
 
 ${dirs}
 """
 
+reftest_template = """# THIS FILE IS AUTOGENERATED BY ${caller} - DO NOT EDIT
+
+${reftests}
+"""
+
 
 
 def makefileString(entries):
     if not len(entries):
         return "  $(NULL)"
     return "\n".join(["  %s \\" % (entry, ) for entry in entries]) + "\n  $(NULL)"
 
 
@@ -56,8 +61,18 @@ def substMakefile(caller, files):
 
 
 def substMozbuild(caller, dirs):
     return string.Template(mozbuild_template).substitute({
         "caller": caller,
         "dirs": mozbuildDirs(dirs),
     })
 
+
+def substReftestList(caller, tests):
+    def reftests(tests):
+        return "\n".join(" ".join(line) for line in tests)
+
+    return string.Template(reftest_template).substitute({
+        "caller": caller,
+        "reftests": reftests(tests),
+    })
+
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -415,18 +415,17 @@ nsObjectFrame::PrepForDrawing(nsIWidget 
     nsAutoTArray<nsIWidget::Configuration,1> configurations;
     nsIWidget::Configuration* configuration = configurations.AppendElement();
     nscoord appUnitsPerDevPixel = presContext->AppUnitsPerDevPixel();
     configuration->mChild = mWidget;
     configuration->mBounds.width = NSAppUnitsToIntPixels(mRect.width, appUnitsPerDevPixel);
     configuration->mBounds.height = NSAppUnitsToIntPixels(mRect.height, appUnitsPerDevPixel);
     parentWidget->ConfigureChildren(configurations);
 
-    nsRefPtr<nsDeviceContext> dx;
-    viewMan->GetDeviceContext(*getter_AddRefs(dx));
+    nsRefPtr<nsDeviceContext> dx = viewMan->GetDeviceContext();
     mInnerView->AttachWidgetEventHandler(mWidget);
 
 #ifdef XP_MACOSX
     // On Mac, we need to invalidate ourselves since even windowed
     // plugins are painted through Thebes and we need to ensure
     // the Thebes layer containing the plugin is updated.
     if (parentWidget == GetNearestWidget()) {
       InvalidateFrame();
--- a/layout/reftests/bidi/dirAuto/reftest.list
+++ b/layout/reftests/bidi/dirAuto/reftest.list
@@ -1,66 +1,15 @@
 == bdi-auto-dir-default.html bdi-auto-dir-default-ref.html
-== dir_auto-contained-bdi-L.html dir_auto-contained-bdi-L-ref.html
-== dir_auto-contained-bdi-R.html dir_auto-contained-bdi-R-ref.html
-== dir_auto-contained-dir-L.html dir_auto-contained-dir-L-ref.html
-== dir_auto-contained-dir-R.html dir_auto-contained-dir-R-ref.html
 == dir_auto-set-contained-dir-L.html dir_auto-contained-dir-L-ref.html
 == dir_auto-set-contained-dir-R.html dir_auto-contained-dir-R-ref.html
 == dir_auto-set-contained-invalid-dir-L.html dir_auto-contained-dir-L-ref.html
 == dir_auto-set-contained-invalid-dir-R.html dir_auto-contained-dir-R-ref.html
 == dir_auto-unset-contained-dir-L.html dir_auto-unset-contained-dir-L-ref.html
 == dir_auto-unset-contained-dir-R.html dir_auto-unset-contained-dir-R-ref.html
-== dir_auto-contained-dir_auto-L.html dir_auto-contained-dir_auto-L-ref.html
-== dir_auto-contained-dir_auto-R.html dir_auto-contained-dir_auto-R-ref.html
-== dir_auto-contained-L.html dir_auto-contained-L-ref.html
-== dir_auto-contained-R.html dir_auto-contained-R-ref.html
-== dir_auto-contained-script-L.html dir_auto-contained-script-L-ref.html
-== dir_auto-contained-script-R.html dir_auto-contained-script-R-ref.html
-== dir_auto-contained-style-L.html dir_auto-contained-style-L-ref.html
-== dir_auto-contained-style-R.html dir_auto-contained-style-R-ref.html
-== dir_auto-contained-textarea-L.html dir_auto-contained-textarea-L-ref.html
-== dir_auto-contained-textarea-R.html dir_auto-contained-textarea-R-ref.html
-== dir_auto-EN-L.html dir_auto-EN-L-ref.html
-== dir_auto-EN-R.html dir_auto-EN-R-ref.html
-== dir_auto-input-EN-L.html dir_auto-input-EN-L-ref.html
-== dir_auto-input-EN-R.html dir_auto-input-EN-R-ref.html
-== dir_auto-input-L.html dir_auto-input-L-ref.html
-== dir_auto-input-N-EN-L.html dir_auto-input-N-EN-L-ref.html
-== dir_auto-input-N-EN-R.html dir_auto-input-N-EN-R-ref.html
-== dir_auto-input-N-EN.html dir_auto-input-N-EN-ref.html
-== dir_auto-input-N-L.html dir_auto-input-N-L-ref.html
-== dir_auto-input-N-R.html dir_auto-input-N-R-ref.html
-== dir_auto-input-R.html dir_auto-input-R-ref.html
-== dir_auto-input-script-EN-L.html dir_auto-input-script-EN-L-ref.html
-== dir_auto-input-script-EN-R.html dir_auto-input-script-EN-R-ref.html
-== dir_auto-input-script-L.html dir_auto-input-script-L-ref.html
-== dir_auto-input-script-N-EN-L.html dir_auto-input-script-N-EN-L-ref.html
-== dir_auto-input-script-N-EN-R.html dir_auto-input-script-N-EN-R-ref.html
-== dir_auto-input-script-N-EN.html dir_auto-input-script-N-EN-ref.html
-== dir_auto-input-script-N-L.html dir_auto-input-script-N-L-ref.html
-== dir_auto-input-script-N-R.html dir_auto-input-script-N-R-ref.html
-== dir_auto-input-script-R.html dir_auto-input-script-R-ref.html
-== dir_auto-isolate.html dir_auto-isolate-ref.html
-== dir_auto-L.html dir_auto-L-ref.html
-== dir_auto-N-EN-L.html dir_auto-N-EN-L-ref.html
-== dir_auto-N-EN-R.html dir_auto-N-EN-R-ref.html
-== dir_auto-N-EN.html dir_auto-N-EN-ref.html
-== dir_auto-N-L.html dir_auto-N-L-ref.html
-== dir_auto-N-R.html dir_auto-N-R-ref.html
-== dir_auto-pre-mixed.html dir_auto-pre-mixed-ref.html
-== dir_auto-pre-N-between-Rs.html dir_auto-pre-N-between-Rs-ref.html
-== dir_auto-pre-N-EN.html dir_auto-pre-N-EN-ref.html
-== dir_auto-R.html dir_auto-R-ref.html
-== dir_auto-textarea-mixed.html dir_auto-textarea-mixed-ref.html
-== dir_auto-textarea-N-between-Rs.html dir_auto-textarea-N-between-Rs-ref.html
-== dir_auto-textarea-N-EN.html dir_auto-textarea-N-EN-ref.html
-== dir_auto-textarea-script-mixed.html dir_auto-textarea-script-mixed-ref.html
-== dir_auto-textarea-script-N-between-Rs.html dir_auto-textarea-script-N-between-Rs-ref.html
-== dir_auto-textarea-script-N-EN.html dir_auto-textarea-script-N-EN-ref.html
 == dynamicDirAuto-setLTR-Auto1.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-Auto2.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-Auto3.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-Auto4.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-Auto5.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-Auto6.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-LTR1.html dynamicDirAuto-refLTR-LTR.html
 == dynamicDirAuto-setLTR-LTR2.html dynamicDirAuto-refLTR-LTR.html
--- a/layout/reftests/reftest.list
+++ b/layout/reftests/reftest.list
@@ -316,16 +316,17 @@ skip-if(B2G) include ../xul/base/reftest
 skip-if(B2G) include ../xul/grid/reftests/reftest.list
 
 # z-index/
 skip-if(B2G) include z-index/reftest.list
 
 # reftest(s) to verify content bugfixes
 skip-if(B2G) include ../../content/html/document/reftests/reftests.list
 skip-if(B2G) include ../../content/html/content/reftests/reftest.list
+skip-if(B2G) include ../../dom/imptests/reftest.list
 
 # editor/
 skip-if(B2G) include ../../editor/reftests/reftest.list
 
 # box-sizing
 skip-if(B2G) include box-sizing/reftest.list
 
 # invalidation - only run on B2G
--- a/python/mach/mach/logging.py
+++ b/python/mach/mach/logging.py
@@ -103,17 +103,17 @@ class StructuredTerminalFormatter(Struct
         if not self.terminal:
             return s
 
         result = s
 
         if s.startswith('TEST-PASS'):
             result = self.terminal.green(s[0:9]) + s[9:]
         elif s.startswith('TEST-UNEXPECTED'):
-            result = self.terminal.red(s[0:20]) + s[21:]
+            result = self.terminal.red(s[0:20]) + s[20:]
 
         return result
 
 
 class LoggingManager(object):
     """Holds and controls global logging state.
 
     An application should instantiate one of these and configure it as needed.
--- a/python/psutil/CREDITS
+++ b/python/psutil/CREDITS
@@ -13,16 +13,17 @@ Really thanks to all of you.
 
 
 Maintainers
 ===========
 
 N: Giampaolo Rodola'
 C: Italy
 E: g.rodola@gmail.com
+W: http://www.linkedin.com/in/grodola
 
 N: Jay Loden
 C: NJ, USA
 E: jloden@gmail.com
 W: http://www.jayloden.com
 
 
 Contributors
@@ -73,17 +74,17 @@ E: sandro.tosi@gmail.com
 I: 200, 201
 
 N: Andrew Colin
 E: andrew.colin@gmail.com
 I: 248
 
 N: Amoser
 E: amoser@google.com
-I: 266, 267
+I: 266, 267, 340
 
 N: Matthew Grant
 E: matthewgrant5@gmail.com
 I: 271
 
 N: oweidner
 E: oweidner@cct.lsu.edu
 I: 275
@@ -112,8 +113,52 @@ I: 314
 N: Kim Gräsman
 E: kim.grasman@gmail.com
 D: ...also kindly donated some money.
 I: 316
 
 N: Riccardo Murri
 C: Italy
 I: 318
+
+N: Florent Xicluna
+E: florent.xicluna@gmail.com
+I: 319
+
+N: Michal Spondr
+E: michal.spondr
+I: 313
+
+N: Jean Sebastien
+E: dumbboules@gmail.com
+I: 344
+
+N: Rob Smith
+W: http://www.kormoc.com/
+I: 341
+
+N: Youngsik Kim
+W: https://plus.google.com/101320747613749824490/
+I: 317
+
+N: Gregory Szorc
+W: https://plus.google.com/116873264322260110710/posts
+I: 323
+
+N: André Oriani
+E: aoriani@gmail.com
+I: 361
+
+N: clackwell
+E: clackwell@gmail.com
+I: 356
+
+N: m.malycha
+E: m.malycha@gmail.com
+I: 351
+
+N: John Baldwin
+E: jhb@FreeBSD.org
+I: 370
+
+N: Jan Beich
+E: jbeich@tormail.org
+I: 325
--- a/python/psutil/HISTORY
+++ b/python/psutil/HISTORY
@@ -1,187 +1,261 @@
 Bug tracker at http://code.google.com/p/psutil/issues
 
+0.7.1 - 2013-05-03
+------------------
+
+BUG FIXES:
+
+ * #325: [BSD] psutil.virtual_memory() can raise SystemError.
+         (patch by Jan Beich)
+ * #370: [BSD] Process.get_connections() requires root.  (patch by John Baldwin)
+ * #372: [BSD] different process methods raise NoSuchProcess instead of
+         AccessDenied.
+
+
+0.7.0 - 2013-04-12
+------------------
+
+NEW FEATURES
+
+ * #233: code migrated to Mercurial (yay!)
+ * #246: psutil.error module is deprecated and scheduled for removal.
+ * #328: [Windows] process IO nice/priority support.
+ * #359: psutil.get_boot_time()
+ * #361: [Linux] psutil.cpu_times() now includes new 'steal', 'guest' and
+         'guest_nice' fields available on recent Linux kernels.
+         Also, psutil.cpu_percent() is more accurate.
+ * #362: cpu_times_percent() (per-CPU-time utilization as a percentage)
+
+BUG FIXES
+
+ * #234: [Windows] disk_io_counters() fails to list certain disks.
+ * #264: [Windows] use of psutil.disk_partitions() may cause a message box to
+         appear.
+ * #313: [Linux] psutil.virtual_memory() and psutil.swap_memory() can crash on
+         certain exotic Linux flavors having an incomplete /proc interface.
+         If that's the case we now set the unretrievable stats to 0 and raise a
+         RuntimeWarning.
+ * #315: [OSX] fix some compilation warnings.
+ * #317: [Windows] cannot set process CPU affinity above 31 cores.
+ * #319: [Linux] process get_memory_maps() raises KeyError 'Anonymous' on Debian
+         squeeze.
+ * #321: [UNIX] Process.ppid property is no longer cached as the kernel may set
+         the ppid to 1 in case of a zombie process.
+ * #323: [OSX] disk_io_counters()'s read_time and write_time parameters were
+         reporting microseconds not milliseconds.  (patch by Gregory Szorc)
+ * #331: Process cmdline is no longer cached after first acces as it may change.
+ * #333: [OSX] Leak of Mach ports on OS X (patch by rsesek@google.com)
+ * #337: [Linux] process methods not working because of a poor /proc
+         implementation will raise NotImplementedError rather than RuntimeError
+         and Process.as_dict() will not blow up.  (patch by Curtin1060)
+ * #338: [Linux] disk_io_counters() fails to find some disks.
+ * #339: [FreeBSD] get_pid_list() can allocate all the memory on system.
+ * #341: [Linux] psutil might crash on import due to error in retrieving system
+         terminals map.
+ * #344: [FreeBSD] swap_memory() might return incorrect results due to
+         kvm_open(3) not being called. (patch by Jean Sebastien)
+ * #338: [Linux] disk_io_counters() fails to find some disks.
+ * #351: [Windows] if psutil is compiled with mingw32 (provided installers for
+         py2.4 and py2.5 are) disk_io_counters() will fail. (Patch by m.malycha)
+ * #353: [OSX] get_users() returns an empty list on OSX 10.8.
+ * #356: Process.parent now checks whether parent PID has been reused in which
+         case returns None.
+ * #365: Process.set_nice() should check PID has not been reused by another
+         process.
+ * #366: [FreeBSD] get_memory_maps(), get_num_fds(), get_open_files() and
+         getcwd() Process methods raise RuntimeError instead of AccessDenied.
+
+API CHANGES
+
+ * Process.cmdline property is no longer cached after first access.
+ * Process.ppid property is no longer cached after first access.
+ * [Linux] Process methods not working because of a poor /proc implementation
+   will raise NotImplementedError instead of RuntimeError.
+ * psutil.error module is deprecated and scheduled for removal.
+
+
 0.6.1 - 2012-08-16
 ------------------
 
 NEW FEATURES
 
- * Issue 316: process cmdline property now makes a better job at guessing the
-   process executable from the cmdline.
+ * #316: process cmdline property now makes a better job at guessing the process
+         executable from the cmdline.
 
 BUG FIXES
 
- * Issue 316: process exe was resolved in case it was a symlink.
- * Issue 318: python 2.4 compatibility was broken.
+ * #316: process exe was resolved in case it was a symlink.
+ * #318: python 2.4 compatibility was broken.
 
 API CHANGES
 
  * process exe can now return an empty string instead of raising AccessDenied.
  * process exe is no longer resolved in case it's a symlink.
 
 
 0.6.0 - 2012-08-13
 ------------------
 
 NEW FEATURES
 
- * Issue 216: (UNIX) get_connections() UNIX sockets support.
- * Issue 220: (BSD) get_connections() has been rewritten in C and no longer
-   requires lsof.
- * Issue 222: (OSX) add support for process cwd.
- * Issue 261: process extended memory info.
- * Issue 295: (OSX) process executable path is now determined by asking the OS
-   instead of being guessed from process cmdline.
- * Issue 297: (OSX) the Process methods below were always raising AccessDenied
-   for any process except the current one. Now this is no longer true. Also they
-   are 2.5x faster.
-    - name
-    - get_memory_info()
-    - get_memory_percent()
-    - get_cpu_times()
-    - get_cpu_percent()
-    - get_num_threads()
- * Issue 300: examples/pmap.py script.
- * Issue 301: process_iter() now yields processes sorted by their PIDs.
- * Issue 302: process number of voluntary and involuntary context switches.
- * Issue 303: (Windows) the Process methods below were always raising
-   AccessDenied for any process not owned by current user. Now this is no longer
-   true:
-    - create_time
-    - get_cpu_times()
-    - get_cpu_percent()
-    - get_memory_info()
-    - get_memory_percent()
-    - get_num_handles()
-    - get_io_counters()
- * Issue 305: add examples/netstat.py script.
- * Issue 311: system memory functions has been refactorized and rewritten and
-   now provide a more detailed and consistent representation of the system
-   memory.
-   New psutil.virtual_memory() function provides the following memory amounts:
-    - total
-    - available
-    - percent
-    - used
-    - active (UNIX)
-    - inactive (UNIX)
-    - buffers (BSD, Linux)
-    - cached (BSD, OSX)
-    - wired (OSX, BSD)
-    - shared (BSD)
-   New psutil.swap_memory() provides:
-    - total
-    - used
-    - free
-    - percent
-    - sin (no. of bytes the system has swapped in from disk (cumulative))
-    - sout (no. of bytes the system has swapped out from disk (cumulative))
-   All old memory-related functions are deprecated.
-   Also two new example scripts were added:  free.py and meminfo.py.
- * Issue 312: psutil.network_io_counters() namedtuple includes 4 new fields:
-   errin, errout dropin and dropout, reflecting the number of packets dropped
-   and with errors.
+ * #216: [POSIX] get_connections() UNIX sockets support.
+ * #220: [FreeBSD] get_connections() has been rewritten in C and no longer
+         requires lsof.
+ * #222: [OSX] add support for process cwd.
+ * #261: process extended memory info.
+ * #295: [OSX] process executable path is now determined by asking the OS
+         instead of being guessed from process cmdline.
+ * #297: [OSX] the Process methods below were always raising AccessDenied for
+         any process except the current one. Now this is no longer true. Also
+         they are 2.5x faster.
+           - name
+           - get_memory_info()
+           - get_memory_percent()
+           - get_cpu_times()
+           - get_cpu_percent()
+           - get_num_threads()
+ * #300: examples/pmap.py script.
+ * #301: process_iter() now yields processes sorted by their PIDs.
+ * #302: process number of voluntary and involuntary context switches.
+ * #303: [Windows] the Process methods below were always raising AccessDenied
+         for any process not owned by current user. Now this is no longer true:
+          - create_time
+          - get_cpu_times()
+          - get_cpu_percent()
+          - get_memory_info()
+          - get_memory_percent()
+          - get_num_handles()
+          - get_io_counters()
+ * #305: add examples/netstat.py script.
+ * #311: system memory functions has been refactorized and rewritten and now
+         provide a more detailed and consistent representation of the system
+         memory. New psutil.virtual_memory() function provides the following
+         memory amounts:
+          - total
+          - available
+          - percent
+          - used
+          - active [POSIX]
+          - inactive [POSIX]
+          - buffers (BSD, Linux)
+          - cached (BSD, OSX)
+          - wired (OSX, BSD)
+          - shared [FreeBSD]
+         New psutil.swap_memory() provides:
+          - total
+          - used
+          - free
+          - percent
+          - sin (no. of bytes the system has swapped in from disk (cumulative))
+          - sout (no. of bytes the system has swapped out from disk (cumulative))
+         All old memory-related functions are deprecated.
+         Also two new example scripts were added:  free.py and meminfo.py.
+ * #312: psutil.network_io_counters() namedtuple includes 4 new fields:
+         errin, errout dropin and dropout, reflecting the number of packets
+         dropped and with errors.
 
 BUGFIXES
 
- * Issue 298: (OSX - BSD) memory leak in get_num_fds().
- * Issue 299: potential memory leak every time PyList_New(0) is used.
- * Issue 303: (Windows) potential heap corruption in get_num_threads() and
-   get_status() Process methods.
- * Issue 305: (BSD) psutil can't compile on FreeBSD 9 due to removal of utmp.h.
- * Issue 306: at C level, errors are not checked when invoking Py* functions
-   which create or manipulate Python objects leading to potential memory related
-   errors and/or segmentation faults.
- * Issue 307: (BSD) values returned by psutil.network_io_counters() are wrong.
- * Issue 308: (BSD / Windows) psutil.virtmem_usage() wasn't actually returning
-   information about swap memory usage as it was supposed to do. It does now.
- * Issue 309: get_open_files() might not return files which can not be accessed
-   due to limited permissions. AccessDenied is now raised instead.
+ * #298: [OSX and BSD] memory leak in get_num_fds().
+ * #299: potential memory leak every time PyList_New(0) is used.
+ * #303: [Windows] potential heap corruption in get_num_threads() and
+         get_status() Process methods.
+ * #305: [FreeBSD] psutil can't compile on FreeBSD 9 due to removal of utmp.h.
+ * #306: at C level, errors are not checked when invoking Py* functions which
+         create or manipulate Python objects leading to potential memory related
+         errors and/or segmentation faults.
+ * #307: [FreeBSD] values returned by psutil.network_io_counters() are wrong.
+ * #308: [BSD / Windows] psutil.virtmem_usage() wasn't actually returning
+         information about swap memory usage as it was supposed to do. It does
+         now.
+ * #309: get_open_files() might not return files which can not be accessed
+         due to limited permissions. AccessDenied is now raised instead.
 
 API CHANGES
 
  * psutil.phymem_usage() is deprecated             (use psutil.virtual_memory())
  * psutil.virtmem_usage() is deprecated            (use psutil.swap_memory())
  * psutil.phymem_buffers() on Linux is deprecated  (use psutil.virtual_memory())
  * psutil.cached_phymem() on Linux is deprecated   (use psutil.virtual_memory())
- * (Windows and BSD) psutil.virtmem_usage() now returns information about swap
+ * [Windows and BSD] psutil.virtmem_usage() now returns information about swap
    memory instead of virtual memory.
 
 
 0.5.1 - 2012-06-29
 ------------------
 
 NEW FEATURES
 
- * Issue 293: (Windows) process executable path is now determined by asking the
-   OS instead of being guessed from process cmdline.
+ * #293: [Windows] process executable path is now determined by asking the OS
+         instead of being guessed from process cmdline.
 
 BUGFIXES
 
- * Issue 292: (Linux) race condition in process files/threads/connections.
- * Issue 294: (Windows) Process CPU affinity is only able to set CPU #0.
+ * #292: [Linux] race condition in process files/threads/connections.
+ * #294: [Windows] Process CPU affinity is only able to set CPU #0.
 
 
 0.5.0 - 2012-06-27
 ------------------
 
 NEW FEATURES
 
- * Issue #195: (Windows) number of handles opened by process.
- * Issue #209: psutil.disk_partitions() now provides also mount options.
- * Issue #229: list users currently connected on the system (psutil.get_users()).
- * Issue #238: (Linux, Windows) process CPU affinity (get and set).
- * Issue #242: Process.get_children(recursive=True): return all process
-   descendants.
- * Issue #245: (POSIX) Process.wait() incrementally consumes less CPU cycles.
- * Issue #257: (Windows) removed Windows 2000 support.
- * Issue #258: (Linux) Process.get_memory_info() is now 0.5x faster.
- * Issue #260: process's mapped memory regions. (Windows patch by wj32.64, OSX
-   patch by Jeremy Whitlock)
- * Issue #262: (Windows) psutil.disk_partitions() was slow due to inspecting
-   the floppy disk drive also when "all" argument was False.
- * Issue #273: psutil.get_process_list() is deprecated.
- * Issue #274: psutil no longer requires 2to3 at installation time in order to
-   work with Python 3.
- * Issue #278: new Process.as_dict() method.
- * Issue #281: ppid, name, exe, cmdline and create_time properties of Process
-   class are now cached after being accessed.
- * Issue #282: psutil.STATUS_* constants can now be compared by using their
-   string representation.
- * Issue #283: speedup Process.is_running() by caching its return value in case
-   the process is terminated.
- * Issue #284: (POSIX) per-process number of opened file descriptors.
- * Issue #287: psutil.process_iter() now caches Process instances between calls.
- * Issue #290: Process.nice property is deprecated in favor of new get_nice()
-   and set_nice() methods.
+ * #195: [Windows] number of handles opened by process.
+ * #209: psutil.disk_partitions() now provides also mount options.
+ * #229: list users currently connected on the system (psutil.get_users()).
+ * #238: [Linux, Windows] process CPU affinity (get and set).
+ * #242: Process.get_children(recursive=True): return all process
+         descendants.
+ * #245: [POSIX] Process.wait() incrementally consumes less CPU cycles.
+ * #257: [Windows] removed Windows 2000 support.
+ * #258: [Linux] Process.get_memory_info() is now 0.5x faster.
+ * #260: process's mapped memory regions. (Windows patch by wj32.64, OSX patch
+         by Jeremy Whitlock)
+ * #262: [Windows] psutil.disk_partitions() was slow due to inspecting the
+         floppy disk drive also when "all" argument was False.
+ * #273: psutil.get_process_list() is deprecated.
+ * #274: psutil no longer requires 2to3 at installation time in order to work
+         with Python 3.
+ * #278: new Process.as_dict() method.
+ * #281: ppid, name, exe, cmdline and create_time properties of Process class
+         are now cached after being accessed.
+ * #282: psutil.STATUS_* constants can now be compared by using their string
+         representation.
+ * #283: speedup Process.is_running() by caching its return value in case the
+         process is terminated.
+ * #284: [POSIX] per-process number of opened file descriptors.
+ * #287: psutil.process_iter() now caches Process instances between calls.
+ * #290: Process.nice property is deprecated in favor of new get_nice() and
+         set_nice() methods.
 
 BUGFIXES
 
- * Issue #193: psutil.Popen constructor can throw an exception if the spawned
-   process terminates quickly.
- * Issue #240: (OSX) incorrect use of free() for Process.get_connections().
- * Issue #244: (POSIX) Process.wait() can hog CPU resources if called against
-   a process which is not our children.
- * Issue #248: (Linux) psutil.network_io_counters() might return erroneous NIC
-   names.
- * Issue #252: (Windows) process getcwd() erroneously raise NoSuchProcess for
-   processes owned by another user.  It now raises AccessDenied instead.
- * Issue #266: (Windows) psutil.get_pid_list() only shows 1024 processes.
-   (patch by Amoser)
- * Issue #267: (OSX) Process.get_connections() - an erroneous remote address
-   was returned. (Patch by Amoser)
- * Issue #272: (Linux) Porcess.get_open_files() - potential race condition can
-   lead to unexpected NoSuchProcess exception.  Also, we can get incorrect
-   reports of not absolutized path names.
- * Issue #275: (Linux) Process.get_io_counters() erroneously raise NoSuchProcess
-   on old Linux versions. Where not available it now raises NotImplementedError.
- * Issue #286: Process.is_running() doesn't actually check whether PID has been
-   reused.
- * Issue #314: Process.get_children() can sometimes return non-children.
+ * #193: psutil.Popen constructor can throw an exception if the spawned process
+         terminates quickly.
+ * #240: [OSX] incorrect use of free() for Process.get_connections().
+ * #244: [POSIX] Process.wait() can hog CPU resources if called against a
+         process which is not our children.
+ * #248: [Linux] psutil.network_io_counters() might return erroneous NIC names.
+ * #252: [Windows] process getcwd() erroneously raise NoSuchProcess for
+         processes owned by another user.  It now raises AccessDenied instead.
+ * #266: [Windows] psutil.get_pid_list() only shows 1024 processes.
+         (patch by Amoser)
+ * #267: [OSX] Process.get_connections() - an erroneous remote address was
+         returned. (Patch by Amoser)
+ * #272: [Linux] Porcess.get_open_files() - potential race condition can lead to
+         unexpected NoSuchProcess exception.  Also, we can get incorrect reports
+         of not absolutized path names.
+ * #275: [Linux] Process.get_io_counters() erroneously raise NoSuchProcess on
+         old Linux versions. Where not available it now raises
+         NotImplementedError.
+ * #286: Process.is_running() doesn't actually check whether PID has been
+         reused.
+ * #314: Process.get_children() can sometimes return non-children.
 
 API CHANGES
 
  * Process.nice property is deprecated in favor of new get_nice() and set_nice()
    methods.
  * psutil.get_process_list() is deprecated.
  * ppid, name, exe, cmdline and create_time properties of Process class are now
    cached after being accessed, meaning NoSuchProcess will no longer be raised
@@ -190,175 +264,174 @@ API CHANGES
    representation.
 
 
 0.4.1 - 2011-12-14
 ------------------
 
 BUGFIXES
 
- * Issue 228: some example scripts were not working with python 3.
- * Issue 230: (Windows / OSX) memory leak in Process.get_connections().
- * Issue 232: (Linux) psutil.phymem_usage() can report erroneous values which
-   are different than "free" command.
- * Issue 236: (Windows) memory/handle leak in Process's get_memory_info(),
-   suspend() and resume() methods.
+ * #228: some example scripts were not working with python 3.
+ * #230: [Windows / OSX] memory leak in Process.get_connections().
+ * #232: [Linux] psutil.phymem_usage() can report erroneous values which are
+         different than "free" command.
+ * #236: [Windows] memory/handle leak in Process's get_memory_info(),
+         suspend() and resume() methods.
 
 
 0.4.0 - 2011-10-29
 ------------------
 
 NEW FEATURES
 
- * Issue 150: network I/O counters. (OSX and Windows patch by Jeremy Whitlock)
- * Issue 154: (FreeBSD) add support for process getcwd()
- * Issue 157: (Windows) provide installer for Python 3.2 64-bit.
- * Issue 198: Process.wait(timeout=0) can now be used to make wait() return
-   immediately.
- * Issue 206: disk I/O counters. (OSX and Windows patch by Jeremy Whitlock)
- * Issue 213: examples/iotop.py script.
- * Issue 217: Process.get_connections() now has a "kind" argument to filter
+ * #150: network I/O counters. (OSX and Windows patch by Jeremy Whitlock)
+ * #154: [FreeBSD] add support for process getcwd()
+ * #157: [Windows] provide installer for Python 3.2 64-bit.
+ * #198: Process.wait(timeout=0) can now be used to make wait() return
+         immediately.
+ * #206: disk I/O counters. (OSX and Windows patch by Jeremy Whitlock)
+ * #213: examples/iotop.py script.
+ * #217: Process.get_connections() now has a "kind" argument to filter
    for connections with different criteria.
- * Issue 221: (FreeBSD) Process.get_open_files has been rewritten in C and no
-   longer relies on lsof.
- * Issue 223: examples/top.py script.
- * Issue 227: examples/nettop.py script.
+ * #221: [FreeBSD] Process.get_open_files has been rewritten in C and no longer
+   relies on lsof.
+ * #223: examples/top.py script.
+ * #227: examples/nettop.py script.
 
 BUGFIXES
 
- * Issue 135: (OS X) psutil cannot create Process object
- * Issue 144: (Linux) no longer support 0 special PID.
- * Issue 188: (Linux) psutil import error on Linux ARM architectures.
- * Issue 194: (POSIX) psutil.Process.get_cpu_percent() now reports a percentage
-   over 100 on multicore processors.
- * Issue 197: (Linux) Process.get_connections() is broken on platforms not
-   supporting IPv6.
- * Issue 200: (Linux) psutil.NUM_CPUS not working on armel and sparc
-   architectures and causing crash on module import.
- * Issue 201: (Linux) Process.get_connections() is broken on big-endian
-   architectures.
- * Issue 211: Process instance can unexpectedly raise NoSuchProcess if tested
-   for equality with another object.
- * Issue 218: (Linux) crash at import time on Debian 64-bit because of a missing
-   line in /proc/meminfo.
- * Issue 226: (FreeBSD) crash at import time on FreeBSD 7 and minor.
+ * #135: [OSX] psutil cannot create Process object.
+ * #144: [Linux] no longer support 0 special PID.
+ * #188: [Linux] psutil import error on Linux ARM architectures.
+ * #194: [POSIX] psutil.Process.get_cpu_percent() now reports a percentage over
+         100 on multicore processors.
+ * #197: [Linux] Process.get_connections() is broken on platforms not supporting
+         IPv6.
+ * #200: [Linux] psutil.NUM_CPUS not working on armel and sparc architectures
+         and causing crash on module import.
+ * #201: [Linux] Process.get_connections() is broken on big-endian
+          architectures.
+ * #211: Process instance can unexpectedly raise NoSuchProcess if tested for
+         equality with another object.
+ * #218: [Linux] crash at import time on Debian 64-bit because of a missing line
+         in /proc/meminfo.
+ * #226: [FreeBSD] crash at import time on FreeBSD 7 and minor.
 
 
 0.3.0 - 2011-07-08
 ------------------
 
 NEW FEATURES
 
- * Issue 125: system per-cpu percentage utilization and times.
- * Issue 163: per-process associated terminal (TTY).
- * Issue 171: added get_phymem() and get_virtmem() functions returning system
-   memory information (total, used, free) and memory percent usage.
-   total_* avail_* and used_* memory functions are deprecated.
- * Issue 172: disk usage statistics.
- * Issue 174: mounted disk partitions.
- * Issue 179: setuptools is now used in setup.py
+ * #125: system per-cpu percentage utilization and times.
+ * #163: per-process associated terminal (TTY).
+ * #171: added get_phymem() and get_virtmem() functions returning system
+         memory information (total, used, free) and memory percent usage.
+         total_* avail_* and used_* memory functions are deprecated.
+ * #172: disk usage statistics.
+ * #174: mounted disk partitions.
+ * #179: setuptools is now used in setup.py
 
 BUGFIXES
 
- * Issue 159: SetSeDebug() does not close handles or unset impersonation on
-   return.
- * Issue 164: wait function raises a TimeoutException when a process returns
-   -1 (Windows).
- * Issue 165: process.status raises an unhandled exception.
- * Issue 166: get_memory_info() leaks handles hogging system resources.
- * Issue 168: psutil.cpu_percent() returns erroneous results when used in
-   non-blocking mode.  (patch by Philip Roberts)
- * Issue 178: OSX - Process.get_threads() leaks memory
- * Issue 180: Windows - Process's get_num_threads() and get_threads() methods
-   can raise NoSuchProcess exception while process still exists.
+ * #159: SetSeDebug() does not close handles or unset impersonation on return.
+ * #164: [Windows] wait function raises a TimeoutException when a process
+         returns -1 .
+ * #165: process.status raises an unhandled exception.
+ * #166: get_memory_info() leaks handles hogging system resources.
+ * #168: psutil.cpu_percent() returns erroneous results when used in
+         non-blocking mode.  (patch by Philip Roberts)
+ * #178: OSX - Process.get_threads() leaks memory
+ * #180: [Windows] Process's get_num_threads() and get_threads() methods can
+         raise NoSuchProcess exception while process still exists.
 
 
 0.2.1 - 2011-03-20
 ------------------
 
 NEW FEATURES
 
- * Issue 64: per-process I/O counters.
- * Issue 116: per-process wait() (wait for process to terminate and return its
-   exit code).
- * Issue 134: per-process get_threads() returning information (id, user and
-   kernel times) about threads opened by process.
- * Issue 136: process executable path on FreeBSD is now determined by asking
-   the kernel instead of guessing it from cmdline[0].
- * Issue 137: per-process real, effective and saved user and group ids.
- * Issue 140: system boot time.
- * Issue 142: per-process get and set niceness (priority).
- * Issue 143: per-process status.
- * Issue 147: per-process I/O nice (priority) - Linux only.
- * Issue 148: psutil.Popen class which tidies up subprocess.Popen and
-   psutil.Process in a unique interface.
- * Issue 152: (OSX) get_process_open_files() implementation has been rewritten
-   in C and no longer relies on lsof resulting in a 3x speedup.
- * Issue 153: (OSX) get_process_connection() implementation has been rewritten
-   in C and no longer relies on lsof resulting in a 3x speedup.
+ * #64: per-process I/O counters.
+ * #116: per-process wait() (wait for process to terminate and return its exit
+         code).
+ * #134: per-process get_threads() returning information (id, user and kernel
+         times) about threads opened by process.
+ * #136: process executable path on FreeBSD is now determined by asking the
+         kernel instead of guessing it from cmdline[0].
+ * #137: per-process real, effective and saved user and group ids.
+ * #140: system boot time.
+ * #142: per-process get and set niceness (priority).
+ * #143: per-process status.
+ * #147: per-process I/O nice (priority) - Linux only.
+ * #148: psutil.Popen class which tidies up subprocess.Popen and psutil.Process
+         in a unique interface.
+ * #152: [OSX] get_process_open_files() implementation has been rewritten
+         in C and no longer relies on lsof resulting in a 3x speedup.
+ * #153: [OSX] get_process_connection() implementation has been rewritten
+         in C and no longer relies on lsof resulting in a 3x speedup.
 
 BUGFIXES
 
- * Issue 83: process cmdline is empty on OSX 64-bit.
- * Issue 130: a race condition can cause IOError exception be raised on
-   Linux if process disappears between open() and subsequent read() calls.
- * Issue 145: WindowsError was raised instead of psutil.AccessDenied when using
-   process resume() or suspend() on Windows.
- * Issue 146: 'exe' property on Linux can raise TypeError if path contains NULL
-   bytes.
- * Issue 151: exe and getcwd() for PID 0 on Linux return inconsistent data.
+ * #83:  process cmdline is empty on OSX 64-bit.
+ * #130: a race condition can cause IOError exception be raised on
+         Linux if process disappears between open() and subsequent read() calls.
+ * #145: WindowsError was raised instead of psutil.AccessDenied when using
+         process resume() or suspend() on Windows.
+ * #146: 'exe' property on Linux can raise TypeError if path contains NULL
+         bytes.
+ * #151: exe and getcwd() for PID 0 on Linux return inconsistent data.
 
 API CHANGES
 
  * Process "uid" and "gid" properties are deprecated in favor of "uids" and
    "gids" properties.
 
 
 0.2.0 - 2010-11-13
 ------------------
 
 NEW FEATURES
 
- * Issue 79: per-process open files.
- * Issue 88: total system physical cached memory.
- * Issue 88: total system physical memory buffers used by the kernel.
- * Issue 91: per-process send_signal() and terminate() methods.
- * Issue 95: NoSuchProcess and AccessDenied exception classes now provide "pid",
-   "name" and "msg" attributes.
- * Issue 97: per-process children.
- * Issue 98: Process.get_cpu_times() and Process.get_memory_info now return
-   a namedtuple instead of a tuple.
- * Issue 103: per-process opened TCP and UDP connections.
- * Issue 107: add support for Windows 64 bit. (patch by cjgohlke)
- * Issue 111: per-process executable name.
- * Issue 113: exception messages now include process name and pid.
- * Issue 114: process username Windows implementation has been rewritten in pure
-   C and no longer uses WMI resulting in a big speedup. Also, pywin32 is no
-   longer required as a third-party dependancy. (patch by wj32)
- * Issue 117: added support for Windows 2000.
- * Issue 123: psutil.cpu_percent() and psutil.Process.cpu_percent() accept a
-   new 'interval' parameter.
- * Issue 129: per-process number of threads.
+ * #79: per-process open files.
+ * #88: total system physical cached memory.
+ * #88: total system physical memory buffers used by the kernel.
+ * #91: per-process send_signal() and terminate() methods.
+ * #95: NoSuchProcess and AccessDenied exception classes now provide "pid",
+        "name" and "msg" attributes.
+ * #97: per-process children.
+ * #98: Process.get_cpu_times() and Process.get_memory_info now return
+        a namedtuple instead of a tuple.
+ * #103: per-process opened TCP and UDP connections.
+ * #107: add support for Windows 64 bit. (patch by cjgohlke)
+ * #111: per-process executable name.
+ * #113: exception messages now include process name and pid.
+ * #114: process username Windows implementation has been rewritten in pure
+         C and no longer uses WMI resulting in a big speedup. Also, pywin32 is no
+         longer required as a third-party dependancy. (patch by wj32)
+ * #117: added support for Windows 2000.
+ * #123: psutil.cpu_percent() and psutil.Process.cpu_percent() accept a
+         new 'interval' parameter.
+ * #129: per-process number of threads.
 
 BUGFIXES
 
- * Issue 80: fixed warnings when installing psutil with easy_install.
- * Issue 81: psutil fails to compile with Visual Studio.
- * Issue 94: suspend() raises OSError instead of AccessDenied.
- * Issue 86: psutil didn't compile against FreeBSD 6.x.
- * Issue 102: orphaned process handles obtained by using OpenProcess in C were
-   left behind every time Process class was instantiated.
- * Issue 111: path and name Process properties report truncated or erroneous
-   values on UNIX.
- * Issue 120: cpu_percent() always returning 100% on OS X.
- * Issue 112: uid and gid properties don't change if process changes effective
-   user/group id at some point.
- * Issue 126: ppid, uid, gid, name, exe, cmdline and create_time properties are
-   no longer cached and correctly raise NoSuchProcess exception if the process
-   disappears.
+ * #80: fixed warnings when installing psutil with easy_install.
+ * #81: psutil fails to compile with Visual Studio.
+ * #94: suspend() raises OSError instead of AccessDenied.
+ * #86: psutil didn't compile against FreeBSD 6.x.
+ * #102: orphaned process handles obtained by using OpenProcess in C were
+         left behind every time Process class was instantiated.
+ * #111: path and name Process properties report truncated or erroneous
+         values on UNIX.
+ * #120: cpu_percent() always returning 100% on OS X.
+ * #112: uid and gid properties don't change if process changes effective
+         user/group id at some point.
+ * #126: ppid, uid, gid, name, exe, cmdline and create_time properties are
+         no longer cached and correctly raise NoSuchProcess exception if the process
+         disappears.
 
 API CHANGES
 
  * psutil.Process.path property is deprecated and works as an alias for "exe"
    property.
  * psutil.Process.kill(): signal argument was removed - to send a signal to the
    process use send_signal(signal) method instead.
  * psutil.Process.get_memory_info() returns a nametuple instead of a tuple.
@@ -372,92 +445,93 @@ API CHANGES
    immediately by default (see issue 123).
 
 
 0.1.3 - 2010-03-02
 ------------------
 
 NEW FEATURES
 
- * Issue 14: per-process username
- * Issue 51: per-process current working directory (Windows and Linux only)
- * Issue 59: Process.is_running() is now 10 times faster
- * Issue 61: added supoprt for FreeBSD 64 bit
- * Issue 71: implemented suspend/resume process
- * Issue 75: python 3 support
+ * #14: per-process username
+ * #51: per-process current working directory (Windows and Linux only)
+ * #59: Process.is_running() is now 10 times faster
+ * #61: added supoprt for FreeBSD 64 bit
+ * #71: implemented suspend/resume process
+ * #75: python 3 support
 
 BUGFIXES
 
- * Issue 36: process cpu_times() and memory_info() functions succeeded also for
-   dead processes while a NoSuchProcess exception is supposed to be raised.
- * Issue 48: incorrect size for mib array defined in getcmdargs for BSD
- * Issue 49: possible memory leak due to missing free() on error condition on
- * Issue 50: fixed getcmdargs() memory fragmentation on BSD
- * Issue 55: test_pid_4 was failing on Windows Vista
- * Issue 57: some unit tests were failing on systems where no swap memory is
-   available
- * Issue 58: is_running() is now called before kill() to make sure we are going
-   to kill the correct process.
- * Issue 73: virtual memory size reported on OS X includes shared library size
- * Issue 77: NoSuchProcess wasn't raised on Process.create_time if kill() was
-   used first.
+ * #36: process cpu_times() and memory_info() functions succeeded also for
+        dead processes while a NoSuchProcess exception is supposed to be raised.
+ * #48: incorrect size for mib array defined in getcmdargs for BSD
+ * #49: possible memory leak due to missing free() on error condition on
+ * #50: fixed getcmdargs() memory fragmentation on BSD
+ * #55: test_pid_4 was failing on Windows Vista
+ * #57: some unit tests were failing on systems where no swap memory is
+        available
+ * #58: is_running() is now called before kill() to make sure we are going
+        to kill the correct process.
+ * #73: virtual memory size reported on OS X includes shared library size
+ * #77: NoSuchProcess wasn't raised on Process.create_time if kill() was
+        used first.
 
 
 0.1.2 - 2009-05-06
 ------------------
 
 NEW FEATURES
 
- * Issue 32: Per-process CPU user/kernel times
- * Issue 33: Process create time
- * Issue 34: Per-process CPU utilization percentage
- * Issue 38: Per-process memory usage (bytes)
- * Issue 41: Per-process memory utilization (percent)
- * Issue 39: System uptime
- * Issue 43: Total system virtual memory
- * Issue 46: Total system physical memory
- * Issue 44: Total system used/free virtual and physical memory
+ * #32: Per-process CPU user/kernel times
+ * #33: Process create time
+ * #34: Per-process CPU utilization percentage
+ * #38: Per-process memory usage (bytes)
+ * #41: Per-process memory utilization (percent)
+ * #39: System uptime
+ * #43: Total system virtual memory
+ * #46: Total system physical memory
+ * #44: Total system used/free virtual and physical memory
 
 BUGFIXES
 
- * Issue 36: NoSuchProcess not raised on Windows when accessing timing methods
- * Issue 40: test_get_cpu_times() failing on FreeBSD and OS X
- * Issue 42: get_memory_percent() raises AccessDenied on Windows
+ * #36: [Windows] NoSuchProcess not raised when accessing timing methods.
+ * #40: test_get_cpu_times() failing on FreeBSD and OS X.
+ * #42: [Windows] get_memory_percent() raises AccessDenied.
 
 
 0.1.1 - 2009-03-06
 ------------------
 
 NEW FEATURES
 
- * Issue 4: FreeBSD support for all functions of psutil
- * Issue 9: Process.uid and Process.gid now retrieve process UID and GID.
- * Issue 11: Support for parent/ppid - Process.parent property returns a
-   Process object representing the parent process, and Process.ppid returns
-   the parent PID.
- * Issue 12 & 15: NoSuchProcess exception now raised when creating an object
-   for a nonexistent process, or when retrieving information about a process
-   that has gone away.
- * Issue 21: AccessDenied exception created for raising access denied errors
-   from OSError or WindowsError on individual platforms.
- * Issue 26: psutil.process_iter() function to iterate over processes as
-   Process objects with a generator.
- * Process objects can now also be compared with == operator for equality
-   (PID, name, command line are compared).
+ * #4: FreeBSD support for all functions of psutil
+ * #9: Process.uid and Process.gid now retrieve process UID and GID.
+ * #11: Support for parent/ppid - Process.parent property returns a
+        Process object representing the parent process, and Process.ppid returns
+        the parent PID.
+ * #12 & 15:
+        NoSuchProcess exception now raised when creating an object
+        for a nonexistent process, or when retrieving information about a process
+        that has gone away.
+ * #21: AccessDenied exception created for raising access denied errors
+        from OSError or WindowsError on individual platforms.
+ * #26: psutil.process_iter() function to iterate over processes as
+        Process objects with a generator.
+ * #?:  Process objects can now also be compared with == operator for equality
+        (PID, name, command line are compared).
 
 BUGFIXES
 
- * Issue 16: Special case for Windows' "System Idle Process" (PID 0) which
-   otherwise would return an "invalid parameter" exception.
- * Issue 17: get_process_list() ignores NoSuchProcess and AccessDenied
-   exceptions during building of the list.
- * Issue 22: Process(0).kill() was failing on Windows with an unset exception
- * Issue 23: Special case for pid_exists(0)
- * Issue 24: Process(0).kill() now raises AccessDenied exception instead of
-   WindowsError.
- * Issue 30: psutil.get_pid_list() was returning two instances of PID 0 on OS
-   X and FreeBSD platforms.
+ * #16: [Windows] Special case for "System Idle Process" (PID 0) which
+        otherwise would return an "invalid parameter" exception.
+ * #17: get_process_list() ignores NoSuchProcess and AccessDenied
+        exceptions during building of the list.
+ * #22: [Windows] Process(0).kill() was failing with an unset exception.
+ * #23: Special case for pid_exists(0)
+ * #24: [Windows] Process(0).kill() now raises AccessDenied exception instead of
+        WindowsError.
+ * #30: psutil.get_pid_list() was returning two instances of PID 0 on OS
+        X and FreeBSD platforms.
 
 
 0.1.0 - 2009-01-27
 ------------------
 
  * Initial release.
deleted file mode 100644
--- a/python/psutil/INSTALL
+++ /dev/null
@@ -1,110 +0,0 @@
-==================
-Using easy_install
-==================
-
-The easiest way to install psutil from sources is using easy_install.
-Get the latest easy_install version from http://pypi.python.org/pypi/setuptools
-and just run:
-
-    easy_install psutil
-
-This should get the most updated psutil version from the Python pypi repository,
-unpack it, compile it and install it automatically.
-
-
-===================================
-Installing on Windows using mingw32
-===================================
-
-After the mingw [1] environment is properly set up on your system you can
-compile Windows sources by entering:
-
-    setup.py build -c mingw32
-
-To compile and install just append the "install" keyword at the end of the
-command line above, like this:
-
-    setup.py build -c mingw32 install
-
-It might be possible that distutils will complain about missing gcc executable.
-That means you have to add mingw bin PATH variable first.
-Entering this line in the command prompt should do the work:
-
-    SET PATH=C:\MinGW\bin;%PATH%
-
-NOTE: this assumes MinGW is installed in C:\MinGW, if not simply replace the
-path in the command above with an appropriate location.
-
-[1] http://www.mingw.org/
-
-
-=========================================
-Installing on Windows using Visual Studio
-=========================================
-
-To use Visual Studio to install psutil, you must have the same version of
-Visual Studio used to compile your installation of Python. For older versions
-of Python that will be Visual Studio 2003. For 2.6 and later it should be
-Visual Studio 2008. If you do not have the requisite version of Visual Studio
-available then it is recommended to use MinGW to compile psutil instead.
-If you do have Visual Studio installed, you can use the basic distutils
-commands:
-
-     setup.py build
-
-...or to install and build:
-
-     setup.py install
-
-distutils should take care of any necessary magic to compile from there.
-
-
-==================
-Installing on OS X
-==================
-
-OS X installation from source will require gcc which you can obtain as part of
-the 'XcodeTools' installer from Apple. Then you can run the standard distutils
-commands.
-To build only:
-
-     python setup.py build
-
-To install and build:
-
-     python setup.py install
-
-NOTE: due to developer's hardware limitations psutil has only been compiled and
-tested on OS X 10.4.11 so may or may not work on other versions.
-
-
-=====================
-Installing on FreeBSD
-=====================
-
-The same compiler used to install Python must be present on the system in order
-to build modules using distutils. Assuming it is installed, you can build using
-the standard distutils commands.
-
-Build only:
-
-     python setup.py build
-
-Install and build:
-
-     python setup.py install
-
-
-===================
-Installing on Linux
-===================
-
-gcc is required and so the python headers. They can easily be installed by using
-the distro package manager. For example, on Ubuntu:
-
-     sudo apt-get install python-dev
-
-Once done, you can install/build psutil with:
-
-     python setup.py install
-
--- a/python/psutil/PKG-INFO
+++ b/python/psutil/PKG-INFO
@@ -1,17 +1,17 @@
 Metadata-Version: 1.1
 Name: psutil
-Version: 0.6.1
+Version: 0.7.1
 Summary: A process and system utilities module for Python
 Home-page: http://code.google.com/p/psutil/
 Author: Giampaolo Rodola
 Author-email: g.rodola <at> gmail <dot> com
 License: License :: OSI Approved :: BSD License
-Download-URL: http://psutil.googlecode.com/files/psutil-0.6.1.tar.gz
+Download-URL: http://psutil.googlecode.com/files/psutil-0.7.1.tar.gz
 Description: ===========
         Quick links
         ===========
         
         * `Home page <http://code.google.com/p/psutil>`_
         * `Download <http://code.google.com/p/psutil/downloads/list>`_
         * `Documentation <http://code.google.com/p/psutil/wiki/Documentation>`_
         
@@ -233,16 +233,17 @@ Classifier: Programming Language :: Pyth
 Classifier: Programming Language :: Python :: 2.4
 Classifier: Programming Language :: Python :: 2.5
 Classifier: Programming Language :: Python :: 2.6
 Classifier: Programming Language :: Python :: 2.7
 Classifier: Programming Language :: Python :: 3
 Classifier: Programming Language :: Python :: 3.0
 Classifier: Programming Language :: Python :: 3.1
 Classifier: Programming Language :: Python :: 3.2
+Classifier: Programming Language :: Python :: 3.3
 Classifier: Topic :: System :: Monitoring
 Classifier: Topic :: System :: Networking
 Classifier: Topic :: System :: Networking :: Monitoring
 Classifier: Topic :: System :: Benchmark
 Classifier: Topic :: System :: Hardware
 Classifier: Topic :: System :: Systems Administration
 Classifier: Topic :: Utilities
 Classifier: Topic :: Software Development :: Libraries
old mode 100644
new mode 100755
--- a/python/psutil/examples/disk_usage.py
+++ b/python/psutil/examples/disk_usage.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: disk_usage.py 1340 2012-06-09 13:42:21Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 List all mounted disk partitions a-la "df -h" command.
 """
 
old mode 100644
new mode 100755
--- a/python/psutil/examples/free.py
+++ b/python/psutil/examples/free.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: free.py 1508 2012-08-13 12:30:07Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'free' cmdline utility.
 """
 
old mode 100644
new mode 100755
--- a/python/psutil/examples/iotop.py
+++ b/python/psutil/examples/iotop.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: iotop.py 1236 2011-12-13 19:00:35Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of iotop (http://guichaz.free.fr/iotop/) showing real time
 disk I/O statistics.
 
old mode 100644
new mode 100755
--- a/python/psutil/examples/killall.py
+++ b/python/psutil/examples/killall.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: killall.py 1143 2011-10-05 19:11:59Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Kill a process by name.
 """
 
old mode 100644
new mode 100755
--- a/python/psutil/examples/meminfo.py
+++ b/python/psutil/examples/meminfo.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: meminfo.py 1509 2012-08-13 12:31:18Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Print system memory information.
 """
 
old mode 100644
new mode 100755
--- a/python/psutil/examples/netstat.py
+++ b/python/psutil/examples/netstat.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: netstat.py 1457 2012-07-14 18:09:36Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'netstat'.
 """
 
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/python/psutil/examples/pmap.py
+++ b/python/psutil/examples/pmap.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: pmap.py 1420 2012-07-08 12:12:01Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'pmap' utility on Linux, 'vmmap' on OSX and 'procstat -v' on BSD.
 Report memory map of a process.
 """
old mode 100644
new mode 100755
--- a/python/psutil/examples/process_detail.py
+++ b/python/psutil/examples/process_detail.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: process_detail.py 1498 2012-07-24 21:41:28Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Print detailed information about a process.
 
 Author: Giampaolo Rodola' <g.rodola@gmail.com>
old mode 100644
new mode 100755
--- a/python/psutil/examples/top.py
+++ b/python/psutil/examples/top.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: top.py 1498 2012-07-24 21:41:28Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of top / htop.
 
 Author: Giampaolo Rodola' <g.rodola@gmail.com>
old mode 100644
new mode 100755
--- a/python/psutil/examples/who.py
+++ b/python/psutil/examples/who.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: who.py 1340 2012-06-09 13:42:21Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'who' command; print information about users who are
 currently logged in.
 """
--- a/python/psutil/psutil/__init__.py
+++ b/python/psutil/psutil/__init__.py
@@ -1,60 +1,61 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
-#
-# $Id: __init__.py 1525 2012-08-16 16:32:03Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """psutil is a module providing convenience functions for managing
 processes and gather system information in a portable way by using
 Python.
 """
 
 from __future__ import division
 
-__version__ = "0.6.1"
+__version__ = "0.7.1"
 version_info = tuple([int(num) for num in __version__.split('.')])
 
 __all__ = [
     # exceptions
     "Error", "NoSuchProcess", "AccessDenied", "TimeoutExpired",
     # constants
     "NUM_CPUS", "TOTAL_PHYMEM", "BOOT_TIME",
     "version_info", "__version__",
     "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
     "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
     "STATUS_WAKING", "STATUS_LOCKED",
     # classes
     "Process", "Popen",
     # functions
-    "test", "pid_exists", "get_pid_list", "process_iter", "get_process_list",
-    "virtual_memory", "swap_memory",
-    "cpu_times", "cpu_percent", "per_cpu_percent",
-    "network_io_counters", "disk_io_counters",
+    "pid_exists", "get_pid_list", "process_iter",                   # proc
+    "virtual_memory", "swap_memory",                                # memory
+    "cpu_times", "cpu_percent", "cpu_times_percent",                # cpu
+    "network_io_counters",                                          # network
+    "disk_io_counters", "disk_partitions", "disk_usage",            # disk
+    "get_users", "get_boot_time",                                   # others
     ]
 
 import sys
 import os
 import time
 import signal
 import warnings
 import errno
 import subprocess
 try:
     import pwd
 except ImportError:
     pwd = None
 
-from psutil.error import Error, NoSuchProcess, AccessDenied, TimeoutExpired
-from psutil._compat import property, callable, defaultdict
+from psutil._error import Error, NoSuchProcess, AccessDenied, TimeoutExpired
 from psutil._common import cached_property
+from psutil._compat import (property, callable, defaultdict, namedtuple,
+                            wraps as _wraps, PY3 as _PY3)
 from psutil._common import (deprecated as _deprecated,
                             nt_disk_iostat as _nt_disk_iostat,
                             nt_net_iostat as _nt_net_iostat,
                             nt_sysmeminfo as _nt_sysmeminfo,
                             isfile_strict as _isfile_strict)
 from psutil._common import (STATUS_RUNNING, STATUS_IDLE, STATUS_SLEEPING,
                             STATUS_DISK_SLEEP, STATUS_STOPPED,
                             STATUS_TRACING_STOP, STATUS_ZOMBIE, STATUS_DEAD,
@@ -92,25 +93,66 @@ else:
 
 __all__.extend(_psplatform.__extra__all__)
 
 NUM_CPUS = _psplatform.NUM_CPUS
 BOOT_TIME = _psplatform.BOOT_TIME
 TOTAL_PHYMEM = _psplatform.TOTAL_PHYMEM
 
 
+def _assert_pid_not_reused(fun):
+    """Decorator which raises NoSuchProcess in case a process is no
+    longer running or its PID has been reused.
+    """
+    @_wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        if not self.is_running():
+            raise NoSuchProcess(self.pid, self._platform_impl._process_name)
+        return fun(self, *args, **kwargs)
+    return wrapper
+
+
 class Process(object):
     """Represents an OS process."""
 
     def __init__(self, pid):
         """Create a new Process object for the given pid.
         Raises NoSuchProcess if pid does not exist.
+
+        Note that most of the methods of this class do not make sure
+        the PID of the process being queried has been reused.
+        That means you might end up retrieving an information referring
+        to another process in case the original one this instance
+        refers to is gone in the meantime.
+
+        The only exceptions for which process identity is pre-emptively
+        checked are:
+         - parent
+         - get_children()
+         - set_nice()
+         - suspend()
+         - resume()
+         - send_signal()
+         - terminate()
+         - kill()
+
+        To prevent this problem for all other methods you can:
+          - use is_running() before querying the process
+          - if you're continuously iterating over a set of Process
+            instances use process_iter() which pre-emptively checks
+            process identity for every yielded instance
         """
+        if not _PY3:
+            if not isinstance(pid, (int, long)):
+                raise TypeError('pid must be an integer')
+        if pid < 0:
+            raise ValueError('pid must be a positive integer')
         self._pid = pid
         self._gone = False
+        self._ppid = None
         # platform-specific modules define an _psplatform.Process
         # implementation class
         self._platform_impl = _psplatform.Process(pid)
         self._last_sys_cpu_times = None
         self._last_proc_cpu_times = None
         # cache creation time for later use in is_running() method
         try:
             self.create_time
@@ -130,16 +172,18 @@ class Process(object):
         else:
             details = "(pid=%s, name=%s)" % (pid, name)
         return "%s.%s%s" % (self.__class__.__module__,
                             self.__class__.__name__, details)
 
     def __repr__(self):
         return "<%s at %s>" % (self.__str__(), id(self))
 
+    # --- utility methods
+
     def as_dict(self, attrs=[], ad_value=None):
         """Utility method returning process information as a hashable
         dictionary.
 
         If 'attrs' is specified it must be a list of strings reflecting
         available Process class's attribute names (e.g. ['get_cpu_times',
         'name']) else all public (read only) attributes are assumed.
 
@@ -180,36 +224,55 @@ class Process(object):
                 if name[3] == '_':
                     name = name[4:]
                 elif name == 'getcwd':
                     name = 'cwd'
             retdict[name] = ret
         return retdict
 
     @property
+    @_assert_pid_not_reused
+    def parent(self):
+        """Return the parent process as a Process object pre-emptively
+        checking whether PID has been reused.
+        If no parent is known return None.
+        """
+        ppid = self.ppid
+        if ppid is not None:
+            try:
+                parent = Process(ppid)
+                if parent.create_time <= self.create_time:
+                    return parent
+                # ...else ppid has been reused by another process
+            except NoSuchProcess:
+                pass
+
+    # --- actual API
+
+    @property
     def pid(self):
         """The process pid."""
         return self._pid
 
-    @cached_property
+    @property
     def ppid(self):
         """The process parent pid."""
-        return self._platform_impl.get_process_ppid()
+        # On POSIX we don't want to cache the ppid as it may unexpectedly
+        # change to 1 (init) in case this process turns into a zombie:
+        # https://code.google.com/p/psutil/issues/detail?id=321
+        # http://stackoverflow.com/questions/356722/
 
-    @property
-    def parent(self):
-        """Return the parent process as a Process object. If no parent
-        pid is known return None.
-        """
-        ppid = self.ppid
-        if ppid is not None:
-            try:
-                return Process(ppid)
-            except NoSuchProcess:
-                pass
+        # XXX should we check creation time here rather than in
+        # Process.parent?
+        if os.name == 'posix':
+            return self._platform_impl.get_process_ppid()
+        else:
+            if self._ppid is None:
+                self._ppid = self._platform_impl.get_process_ppid()
+            return self._ppid
 
     @cached_property
     def name(self):
         """The process name."""
         name = self._platform_impl.get_process_name()
         if os.name == 'posix':
             # On UNIX the name gets truncated to the first 15 characters.
             # If it matches the first part of the cmdline we return that
@@ -256,17 +319,17 @@ class Process(object):
                 # empty string; if that's the case we don't want to
                 # raise AD while guessing from the cmdline
                 try:
                     exe = guess_it(fallback=exe)
                 except AccessDenied:
                     pass
             return exe
 
-    @cached_property
+    @property
     def cmdline(self):
         """The command line process has been called with."""
         return self._platform_impl.get_process_cmdline()
 
     @property
     def status(self):
         """The process current status as a STATUS_* constant."""
         return self._platform_impl.get_process_status()
@@ -329,32 +392,47 @@ class Process(object):
             bytes read and written by the process.
             """
             return self._platform_impl.get_process_io_counters()
 
     def get_nice(self):
         """Get process niceness (priority)."""
         return self._platform_impl.get_process_nice()
 
+    @_assert_pid_not_reused
     def set_nice(self, value):
-        """Set process niceness (priority)."""
+        """Set process niceness (priority) pre-emptively checking
+        whether PID has been reused."""
         return self._platform_impl.set_process_nice(value)
 
-    # available only on Linux
+    # available only on Linux and Windows >= Vista
     if hasattr(_psplatform.Process, "get_process_ionice"):
 
         def get_ionice(self):
-            """Return process I/O niceness (priority) as a namedtuple."""
+            """Return process I/O niceness (priority).
+
+            On Linux this is a (ioclass, value) namedtuple.
+            On Windows it's an integer which can be equal to 2 (normal),
+            1 (low) or 0 (very low).
+
+            Available on Linux and Windows > Vista only.
+            """
             return self._platform_impl.get_process_ionice()
 
         def set_ionice(self, ioclass, value=None):
             """Set process I/O niceness (priority).
-            ioclass is one of the IOPRIO_CLASS_* constants.
-            iodata is a number which goes from 0 to 7. The higher the
+
+            On Linux 'ioclass' is one of the IOPRIO_CLASS_* constants.
+            'value' is a number which goes from 0 to 7. The higher the
             value, the lower the I/O priority of the process.
+
+            On Windows only 'ioclass' is used and it can be set to 2
+            (normal), 1 (low) or 0 (very low).
+
+            Available on Linux and Windows > Vista only.
             """
             return self._platform_impl.set_process_ionice(ioclass, value)
 
     # available on Windows and Linux only
     if hasattr(_psplatform.Process, "get_process_cpu_affinity"):
 
         def get_cpu_affinity(self):
             """Get process current CPU affinity."""
@@ -394,19 +472,20 @@ class Process(object):
         return self._platform_impl.get_process_num_threads()
 
     def get_threads(self):
         """Return threads opened by process as a list of namedtuples
         including thread id and thread CPU times (user/system).
         """
         return self._platform_impl.get_process_threads()
 
+    @_assert_pid_not_reused
     def get_children(self, recursive=False):
         """Return the children of this process as a list of Process
-        objects.
+        objects pre-emptively checking whether PID has been reused.
         If recursive is True return all the parent descendants.
 
         Example (A == this process):
 
          A ─┐

             ├─ B (child) ─┐
             │             └─ X (grandchild) ─┐
@@ -418,20 +497,16 @@ class Process(object):
         B, C, D
         >>> p.get_children(recursive=True)
         B, X, Y, C, D
 
         Note that in the example above if process X disappears
         process Y won't be returned either as the reference to
         process A is lost.
         """
-        if not self.is_running():
-            name = self._platform_impl._process_name
-            raise NoSuchProcess(self.pid, name)
-
         ret = []
         if not recursive:
             for p in process_iter():
                 try:
                     if p.ppid == self.pid:
                         # if child happens to be older than its parent
                         # (self) it means child's PID has been reused
                         if self.create_time <= p.create_time:
@@ -469,20 +544,32 @@ class Process(object):
 
     def get_cpu_percent(self, interval=0.1):
         """Return a float representing the current process CPU
         utilization as a percentage.
 
         When interval is > 0.0 compares process times to system CPU
         times elapsed before and after the interval (blocking).
 
-        When interval is 0.0 or None compares process times to system CPU
-        times elapsed since last call, returning immediately.
-        In this case is recommended for accuracy that this function be
-        called with at least 0.1 seconds between calls.
+        When interval is 0.0 or None compares process times to system
+        CPU times elapsed since last call, returning immediately
+        (non-blocking).
+        In this case is recommended for accuracy that this function
+        be called with at least 0.1 seconds between calls.
+
+        Examples:
+
+          >>> p = psutil.Process(os.getpid())
+          >>> # blocking
+          >>> p.get_cpu_percent(interval=1)
+          2.0
+          >>> # non-blocking (percentage since last call)
+          >>> p.get_cpu_percent(interval=0)
+          2.9
+          >>>
         """
         blocking = interval is not None and interval > 0.0
         if blocking:
             st1 = sum(cpu_times())
             pt1 = self._platform_impl.get_cpu_times()
             time.sleep(interval)
             st2 = sum(cpu_times())
             pt2 = self._platform_impl.get_cpu_times()
@@ -539,18 +626,18 @@ class Process(object):
     def get_ext_memory_info(self):
         """Return a namedtuple with variable fields depending on the
         platform representing extended memory information about
         the process. All numbers are expressed in bytes.
         """
         return self._platform_impl.get_ext_memory_info()
 
     def get_memory_percent(self):
-        """Compare physical system memory to process resident memory and
-        calculate process memory utilization as a percentage.
+        """Compare physical system memory to process resident memory
+        (RSS) and calculate process memory utilization as a percentage.
         """
         rss = self._platform_impl.get_memory_info()[0]
         try:
             return (rss / float(TOTAL_PHYMEM)) * 100
         except ZeroDivisionError:
             return 0.0
 
     def get_memory_maps(self, grouped=True):
@@ -602,98 +689,95 @@ class Process(object):
         udp4            UDP over IPv4
         udp6            UDP over IPv6
         unix            UNIX socket (both UDP and TCP protocols)
         all             the sum of all the possible families and protocols
         """
         return self._platform_impl.get_connections(kind)
 
     def is_running(self):
-        """Return whether this process is running."""
+        """Return whether this process is running.
+        It also checks if PID has been reused by another process in
+        which case returns False.
+        """
         if self._gone:
             return False
         try:
             # Checking if pid is alive is not enough as the pid might
             # have been reused by another process.
             # pid + creation time, on the other hand, is supposed to
             # identify a process univocally.
             return self.create_time == \
                    self._platform_impl.get_process_create_time()
         except NoSuchProcess:
             self._gone = True
             return False
 
+    @_assert_pid_not_reused
     def send_signal(self, sig):
-        """Send a signal to process (see signal module constants).
+        """Send a signal to process pre-emptively checking whether
+        PID has been reused (see signal module constants) .
         On Windows only SIGTERM is valid and is treated as an alias
         for kill().
         """
-        # safety measure in case the current process has been killed in
-        # meantime and the kernel reused its PID
-        if not self.is_running():
-            name = self._platform_impl._process_name
-            raise NoSuchProcess(self.pid, name)
         if os.name == 'posix':
             try:
                 os.kill(self.pid, sig)
             except OSError:
                 err = sys.exc_info()[1]
                 name = self._platform_impl._process_name
                 if err.errno == errno.ESRCH:
+                    self._gone = True
                     raise NoSuchProcess(self.pid, name)
                 if err.errno == errno.EPERM:
                     raise AccessDenied(self.pid, name)
                 raise
         else:
             if sig == signal.SIGTERM:
                 self._platform_impl.kill_process()
             else:
                 raise ValueError("only SIGTERM is supported on Windows")
 
+    @_assert_pid_not_reused
     def suspend(self):
-        """Suspend process execution."""
-        # safety measure in case the current process has been killed in
-        # meantime and the kernel reused its PID
-        if not self.is_running():
-            name = self._platform_impl._process_name
-            raise NoSuchProcess(self.pid, name)
-        # windows
+        """Suspend process execution with SIGSTOP pre-emptively checking
+        whether PID has been reused.
+        On Windows it suspends all process threads.
+        """
         if hasattr(self._platform_impl, "suspend_process"):
+            # windows
             self._platform_impl.suspend_process()
         else:
             # posix
             self.send_signal(signal.SIGSTOP)
 
+    @_assert_pid_not_reused
     def resume(self):
-        """Resume process execution."""
-        # safety measure in case the current process has been killed in
-        # meantime and the kernel reused its PID
-        if not self.is_running():
-            name = self._platform_impl._process_name
-            raise NoSuchProcess(self.pid, name)
-        # windows
+        """Resume process execution with SIGCONT pre-emptively checking
+        whether PID has been reused.
+        On Windows it resumes all process threads.
+        """
         if hasattr(self._platform_impl, "resume_process"):
+            # windows
             self._platform_impl.resume_process()
         else:
             # posix
             self.send_signal(signal.SIGCONT)
 
     def terminate(self):
-        """Terminate the process with SIGTERM.
+        """Terminate the process with SIGTERM pre-emptively checking
+        whether PID has been reused.
         On Windows this is an alias for kill().
         """
         self.send_signal(signal.SIGTERM)
 
+    @_assert_pid_not_reused
     def kill(self):
-        """Kill the current process."""
-        # safety measure in case the current process has been killed in
-        # meantime and the kernel reused its PID
-        if not self.is_running():
-            name = self._platform_impl._process_name
-            raise NoSuchProcess(self.pid, name)
+        """Kill the current process with SIGKILL pre-emptively checking
+        whether PID has been reused."""
         if os.name == 'posix':
             self.send_signal(signal.SIGKILL)
         else:
             self._platform_impl.kill_process()
 
     def wait(self, timeout=None):
         """Wait for process to terminate and, if process is a children
         of the current one also return its exit code, else None.
@@ -750,26 +834,27 @@ class Popen(Process):
     For a complete documentation refers to:
     http://docs.python.org/library/subprocess.html
     """
 
     def __init__(self, *args, **kwargs):
         self.__subproc = subprocess.Popen(*args, **kwargs)
         self._pid = self.__subproc.pid
         self._gone = False
+        self._ppid = None
         self._platform_impl = _psplatform.Process(self._pid)
         self._last_sys_cpu_times = None
         self._last_proc_cpu_times = None
         try:
             self.create_time
         except AccessDenied:
             pass
         except NoSuchProcess:
             raise NoSuchProcess(self._pid, None,
-                                "no process found with pid %s" % pid)
+                                "no process found with pid %s" % self._pid)
 
     def __dir__(self):
         return list(set(dir(Popen) + dir(subprocess.Popen)))
 
     def __getattribute__(self, name):
         try:
             return object.__getattribute__(self, name)
         except AttributeError:
@@ -791,16 +876,20 @@ pid_exists = _psplatform.pid_exists
 
 def process_iter():
     """Return a generator yielding a Process class instance for all
     running processes on the local machine.
 
     Every new Process instance is only created once and then cached
     into an internal table which is updated every time this is used.
 
+    Cached Process instances are checked for identity so that you're
+    safe in case a PID has been reused by another process, in which
+    case the cached instance is updated.
+
     The sorting order in which processes are yielded is based on
     their PIDs.
     """
     def add(pid):
         proc = Process(pid)
         _pmap[proc.pid] = proc
         return proc
 
@@ -845,16 +934,19 @@ def cpu_times(percpu=False):
     Here follows a list of all available attributes:
      - user
      - system
      - idle
      - nice (UNIX)
      - iowait (Linux)
      - irq (Linux, FreeBSD)
      - softirq (Linux)
+     - steal (Linux >= 2.6.11)
+     - guest (Linux >= 2.6.24)
+     - guest_nice (Linux >= 3.2.0)
 
     When percpu is True return a list of nameduples for each CPU.
     First element of the list refers to first CPU, second element
     to second CPU and so on.
     The order of the list is consistent across calls.
     """
     if not percpu:
         return _psplatform.get_system_cpu_times()
@@ -877,16 +969,31 @@ def cpu_percent(interval=0.1, percpu=Fal
     In this case is recommended for accuracy that this function be
     called with at least 0.1 seconds between calls.
 
     When percpu is True returns a list of floats representing the
     utilization as a percentage for each CPU.
     First element of the list refers to first CPU, second element
     to second CPU and so on.
     The order of the list is consistent across calls.
+
+    Examples:
+
+      >>> # blocking, system-wide
+      >>> psutil.cpu_percent(interval=1)
+      2.0
+      >>>
+      >>> # blocking, per-cpu
+      >>> psutil.cpu_percent(interval=1, percpu=True)
+      [2.0, 1.0]
+      >>>
+      >>> # non-blocking (percentage since last call)
+      >>> psutil.cpu_percent(interval=0)
+      2.9
+      >>>
     """
     global _last_cpu_times
     global _last_per_cpu_times
     blocking = interval is not None and interval > 0.0
 
     def calculate(t1, t2):
         t1_all = sum(t1)
         t1_busy = t1_all - t1.idle
@@ -920,16 +1027,78 @@ def cpu_percent(interval=0.1, percpu=Fal
             time.sleep(interval)
         else:
             tot1 = _last_per_cpu_times
         _last_per_cpu_times = cpu_times(percpu=True)
         for t1, t2 in zip(tot1, _last_per_cpu_times):
             ret.append(calculate(t1, t2))
         return ret
 
+
+# Use separate global vars for cpu_times_percent() so that it's
+# independent from cpu_percent() and they can both be used within
+# the same program.
+_last_cpu_times_2 = _last_cpu_times
+_last_per_cpu_times_2 = _last_per_cpu_times
+_ptime_cpu_perc_nt = None
+
+def cpu_times_percent(interval=0.1, percpu=False):
+    """Same as cpu_percent() but provides utilization percentages
+    for each specific CPU time as is returned by cpu_times().
+    For instance, on Linux we'll get:
+
+      >>> cpu_times_percent()
+      cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
+                 irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+      >>>
+
+    interval and percpu arguments have the same meaning as in
+    cpu_percent().
+    """
+    global _last_cpu_times_2
+    global _last_per_cpu_times_2
+    blocking = interval is not None and interval > 0.0
+
+    def calculate(t1, t2):
+        global _ptime_cpu_perc_nt
+        nums = []
+        all_delta = sum(t2) - sum(t1)
+        for field in t1._fields:
+            field_delta = getattr(t2, field) - getattr(t1, field)
+            try:
+                field_perc = (100 * field_delta) / all_delta
+            except ZeroDivisionError:
+                field_perc = 0.0
+            nums.append(round(field_perc, 1))
+        if _ptime_cpu_perc_nt is None:
+            _ptime_cpu_perc_nt = namedtuple('cpupercent', ' '.join(t1._fields))
+        return _ptime_cpu_perc_nt(*nums)
+
+    # system-wide usage
+    if not percpu:
+        if blocking:
+            t1 = cpu_times()
+            time.sleep(interval)
+        else:
+            t1 = _last_cpu_times_2
+        _last_cpu_times_2 = cpu_times()
+        return calculate(t1, _last_cpu_times_2)
+    # per-cpu usage
+    else:
+        ret = []
+        if blocking:
+            tot1 = cpu_times(percpu=True)
+            time.sleep(interval)
+        else:
+            tot1 = _last_per_cpu_times_2
+        _last_per_cpu_times_2 = cpu_times(percpu=True)
+        for t1, t2 in zip(tot1, _last_per_cpu_times_2):
+            ret.append(calculate(t1, t2))
+        return ret
+
 # =====================================================================
 # --- system memory related functions
 # =====================================================================
 
 def virtual_memory():
     """Return statistics about system memory usage as a namedtuple
     including the following fields, expressed in bytes:
 
@@ -1030,16 +1199,19 @@ def disk_io_counters(perdisk=False):
      - write_bytes: number of bytes written
      - read_time:   time spent reading from disk (in milliseconds)
      - write_time:  time spent writing to disk (in milliseconds)
 
     If perdisk is True return the same information for every
     physical disk installed on the system as a dictionary
     with partition names as the keys and the namedutuple
     described above as the values.
+
+    On recent Windows versions 'diskperf -y' command may need to be
+    executed first otherwise this function won't find any disk.
     """
     rawdict = _psplatform.disk_io_counters()
     if not rawdict:
         raise RuntimeError("couldn't find any physical disk")
     if perdisk:
         for disk, fields in rawdict.items():
             rawdict[disk] = _nt_disk_iostat(*fields)
         return rawdict
@@ -1078,16 +1250,22 @@ def network_io_counters(pernic=False):
         return rawdict
     else:
         return _nt_net_iostat(*[sum(x) for x in zip(*rawdict.values())])
 
 # =====================================================================
 # --- other system related functions
 # =====================================================================
 
+def get_boot_time():
+    """Return the system boot time expressed in seconds since the epoch.
+    This is also available as psutil.BOOT_TIME.
+    """
+    return _psplatform.get_system_boot_time()
+
 def get_users():
     """Return users currently connected on the system as a list of
     namedtuples including the following attributes.
 
      - user: the name of the user
      - terminal: the tty or pseudo-tty associated with the user, if any.
      - host: the host name associated with the entry, if any.
      - started: the creation time as a floating point number expressed in
@@ -1161,16 +1339,18 @@ def test():
             pass
         else:
             if pinfo['create_time']:
                 ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
                 if ctime.date() == today_day:
                     ctime = ctime.strftime("%H:%M")
                 else:
                     ctime = ctime.strftime("%b%d")
+            else:
+                ctime = ''
             cputime = time.strftime("%M:%S", time.localtime(sum(pinfo['cpu_times'])))
             user = pinfo['username']
             if os.name == 'nt' and '\\' in user:
                 user = user.split('\\')[1]
             vms = pinfo['memory_info'] and \
                   int(pinfo['memory_info'].vms / 1024) or '?'
             rss = pinfo['memory_info'] and \
                   int(pinfo['memory_info'].rss / 1024) or '?'
--- a/python/psutil/psutil/_common.py
+++ b/python/psutil/psutil/_common.py
@@ -1,12 +1,10 @@
 #/usr/bin/env python
-#
-#$Id: _common.py 1524 2012-08-16 15:06:32Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Common objects shared by all _ps* modules."""
 
 from __future__ import division
 import sys
@@ -164,17 +162,16 @@ if AF_UNIX is not None:
     })
 
 
 del AF_INET, AF_INET6, AF_UNIX, SOCK_STREAM, SOCK_DGRAM, socket
 
 # --- namedtuples
 
 # system
-nt_sys_cputimes = namedtuple('cputimes', 'user nice system idle iowait irq softirq')
 nt_sysmeminfo = namedtuple('usage', 'total used free percent')
 # XXX - would 'available' be better than 'free' as for virtual_memory() nt?
 nt_swapmeminfo = namedtuple('swap', 'total used free percent sin sout')
 nt_diskinfo = namedtuple('usage', 'total used free percent')
 nt_partition = namedtuple('partition',  'device mountpoint fstype opts')
 nt_net_iostat = namedtuple('iostat',
     'bytes_sent bytes_recv packets_sent packets_recv errin errout dropin dropout')
 nt_disk_iostat = namedtuple('iostat', 'read_count write_count read_bytes write_bytes read_time write_time')
--- a/python/psutil/psutil/_compat.py
+++ b/python/psutil/psutil/_compat.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-#
-# $Id: _compat.py 1524 2012-08-16 15:06:32Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Module which provides compatibility with older Python versions."""
 
 __all__ = ["PY3", "int", "long", "xrange", "exec_", "callable",
            "namedtuple", "property", "defaultdict"]
new file mode 100644
--- /dev/null
+++ b/python/psutil/psutil/_error.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""psutil exception classes.
+Not supposed to be used / imported directly.
+Instead use psutil.NoSuchProcess, etc.
+"""
+
+
+class Error(Exception):
+    """Base exception class. All other psutil exceptions inherit
+    from this one.
+    """
+
+class NoSuchProcess(Error):
+    """Exception raised when a process with a certain PID doesn't
+    or no longer exists (zombie).
+    """
+
+    def __init__(self, pid, name=None, msg=None):
+        self.pid = pid
+        self.name = name
+        self.msg = msg
+        if msg is None:
+            if name:
+                details = "(pid=%s, name=%s)" % (self.pid, repr(self.name))
+            else:
+                details = "(pid=%s)" % self.pid
+            self.msg = "process no longer exists " + details
+
+    def __str__(self):
+        return self.msg
+
+
+class AccessDenied(Error):
+    """Exception raised when permission to perform an action is denied."""
+
+    def __init__(self, pid=None, name=None, msg=None):
+        self.pid = pid
+        self.name = name
+        self.msg = msg
+        if msg is None:
+            if (pid is not None) and (name is not None):
+                self.msg = "(pid=%s, name=%s)" % (pid, repr(name))
+            elif (pid is not None):
+                self.msg = "(pid=%s)" % self.pid
+            else:
+                self.msg = ""
+
+    def __str__(self):
+        return self.msg
+
+
+class TimeoutExpired(Error):
+    """Raised on Process.wait(timeout) if timeout expires and process
+    is still alive.
+    """
+
+    def __init__(self, pid=None, name=None):
+        self.pid = pid
+        self.name = name
+        if (pid is not None) and (name is not None):
+            self.msg = "(pid=%s, name=%s)" % (pid, repr(name))
+        elif (pid is not None):
+            self.msg = "(pid=%s)" % self.pid
+        else:
+            self.msg = ""
+
+    def __str__(self):
+        return self.msg
--- a/python/psutil/psutil/_psbsd.py
+++ b/python/psutil/psutil/_psbsd.py
@@ -1,42 +1,60 @@
 #!/usr/bin/env python
-#
-# $Id: _psbsd.py 1498 2012-07-24 21:41:28Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """FreeBSD platform implementation."""
 
 import errno
 import os
 import sys
+import warnings
 
 import _psutil_bsd
 import _psutil_posix
 from psutil import _psposix
-from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
-from psutil._compat import namedtuple
+from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
+from psutil._compat import namedtuple, wraps
 from psutil._common import *
 
 __extra__all__ = []
 
 # --- constants
 
-NUM_CPUS = _psutil_bsd.get_num_cpus()
-BOOT_TIME = _psutil_bsd.get_system_boot_time()
-TOTAL_PHYMEM = _psutil_bsd.get_virtual_mem()[0]
-_TERMINAL_MAP = _psposix._get_terminal_map()
+# Since these constants get determined at import time we do not want to
+# crash immediately; instead we'll set them to None and most likely
+# we'll crash later as they're used for determining process CPU stats
+# and creation_time
+try:
+    NUM_CPUS = _psutil_bsd.get_num_cpus()
+except Exception:
+    NUM_CPUS = None
+    warnings.warn("couldn't determine platform's NUM_CPUS", RuntimeWarning)
+try:
+    TOTAL_PHYMEM = _psutil_bsd.get_virtual_mem()[0]
+except Exception:
+    TOTAL_PHYMEM = None
+    warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
+try:
+    BOOT_TIME = _psutil_bsd.get_system_boot_time()
+except Exception:
+    BOOT_TIME = None
+    warnings.warn("couldn't determine platform's BOOT_TIME", RuntimeWarning)
+
+
 _PAGESIZE = os.sysconf("SC_PAGE_SIZE")
 _cputimes_ntuple = namedtuple('cputimes', 'user nice system idle irq')
 
 # --- public functions
 
+get_system_boot_time = _psutil_bsd.get_system_boot_time
+
 nt_virtmem_info = namedtuple('vmem', ' '.join([
     # all platforms
     'total', 'available', 'percent', 'used', 'free',
     # FreeBSD specific
     'active',
     'inactive',
     'buffers',
     'cached',
@@ -119,24 +137,24 @@ def get_system_users():
 
 get_pid_list = _psutil_bsd.get_pid_list
 pid_exists = _psposix.pid_exists
 get_disk_usage = _psposix.get_disk_usage
 network_io_counters = _psutil_bsd.get_network_io_counters
 disk_io_counters = _psutil_bsd.get_disk_io_counters
 
 
-def wrap_exceptions(method):
-    """Call method(self, pid) into a try/except clause so that if an
-    OSError "No such process" exception is raised we assume the process
-    has died and raise psutil.NoSuchProcess instead.
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError exceptions into
+    NoSuchProcess and AccessDenied.
     """
+    @wraps(fun)
     def wrapper(self, *args, **kwargs):
         try:
-            return method(self, *args, **kwargs)
+            return fun(self, *args, **kwargs)
         except OSError:
             err = sys.exc_info()[1]
             if err.errno == errno.ESRCH:
                 raise NoSuchProcess(self.pid, self._process_name)
             if err.errno in (errno.EPERM, errno.EACCES):
                 raise AccessDenied(self.pid, self._process_name)
             raise
     return wrapper
@@ -174,18 +192,19 @@ class Process(object):
     @wrap_exceptions
     def get_process_cmdline(self):
         """Return process cmdline as a list of arguments."""
         return _psutil_bsd.get_process_cmdline(self.pid)
 
     @wrap_exceptions
     def get_process_terminal(self):
         tty_nr = _psutil_bsd.get_process_tty_nr(self.pid)
+        tmap = _psposix._get_terminal_map()
         try:
-            return _TERMINAL_MAP[tty_nr]
+            return tmap[tty_nr]
         except KeyError:
             return None
 
     @wrap_exceptions
     def get_process_ppid(self):
         """Return process parent pid."""
         return _psutil_bsd.get_process_ppid(self.pid)
 
old mode 100755
new mode 100644
--- a/python/psutil/psutil/_pslinux.py
+++ b/python/psutil/psutil/_pslinux.py
@@ -1,57 +1,53 @@
 #!/usr/bin/env python
-#
-# $Id: _pslinux.py 1513 2012-08-14 11:01:37Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Linux platform implementation."""
 
 from __future__ import division
 
 import os
 import errno
 import socket
 import struct
 import sys
 import base64
 import re
+import warnings
 
 import _psutil_posix
 import _psutil_linux
 from psutil import _psposix
-from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
+from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
 from psutil._common import *
-from psutil._compat import PY3, xrange, long, namedtuple
+from psutil._compat import PY3, xrange, long, namedtuple, wraps
 
 __extra__all__ = [
     "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
     "IOPRIO_CLASS_IDLE",
     "phymem_buffers", "cached_phymem"]
 
 
-def _get_boot_time():
-    """Return system boot time (epoch in seconds)"""
+def get_system_boot_time():
+    """Return the system boot time expressed in seconds since the epoch."""
     f = open('/proc/stat', 'r')
     try:
         for line in f:
             if line.startswith('btime'):
                 return float(line.strip().split()[1])
-        raise RuntimeError("line not found")
+        raise RuntimeError("line 'btime' not found")
     finally:
         f.close()
 
 def _get_num_cpus():
     """Return the number of CPUs on the system"""
-    # we try to determine num CPUs by using different approaches.
-    # SC_NPROCESSORS_ONLN seems to be the safer and it is also
-    # used by multiprocessing module
     try:
         return os.sysconf("SC_NPROCESSORS_ONLN")
     except ValueError:
         # as a second fallback we try to parse /proc/cpuinfo
         num = 0
         f = open('/proc/cpuinfo', 'r')
         try:
             lines = f.readlines()
@@ -72,27 +68,45 @@ def _get_num_cpus():
             f.close()
         search = re.compile('cpu\d')
         for line in lines:
             line = line.split(' ')[0]
             if search.match(line):
                 num += 1
 
     if num == 0:
-        raise RuntimeError("can't determine number of CPUs")
+        raise RuntimeError("couldn't determine platform's NUM_CPUS")
     return num
 
 
 # Number of clock ticks per second
-_CLOCK_TICKS = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
+_CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
 _PAGESIZE = os.sysconf("SC_PAGE_SIZE")
-_TERMINAL_MAP = _psposix._get_terminal_map()
-BOOT_TIME = _get_boot_time()
-NUM_CPUS = _get_num_cpus()
-TOTAL_PHYMEM = _psutil_linux.get_sysinfo()[0]
+
+# Since these constants get determined at import time we do not want to
+# crash immediately; instead we'll set them to None and most likely
+# we'll crash later as they're used for determining process CPU stats
+# and creation_time
+try:
+    BOOT_TIME = get_system_boot_time()
+except Exception:
+    BOOT_TIME = None
+    warnings.warn("couldn't determine platform's BOOT_TIME", RuntimeWarning)
+try:
+    NUM_CPUS = _get_num_cpus()
+except Exception:
+    NUM_CPUS = None
+    warnings.warn("couldn't determine platform's NUM_CPUS", RuntimeWarning)
+try:
+    TOTAL_PHYMEM = _psutil_linux.get_sysinfo()[0]
+except Exception:
+    TOTAL_PHYMEM = None
+    warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
+
+
 # ioprio_* constants http://linux.die.net/man/2/ioprio_get
 IOPRIO_CLASS_NONE = 0
 IOPRIO_CLASS_RT = 1
 IOPRIO_CLASS_BE = 2
 IOPRIO_CLASS_IDLE = 3
 
 # http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
 _TCP_STATES_TABLE = {"01" : "ESTABLISHED",
@@ -131,17 +145,22 @@ def virtual_memory():
                 active = int(line.split()[1]) * 1024
             elif line.startswith('Inactive:'):
                 inactive = int(line.split()[1]) * 1024
             if cached is not None \
             and active is not None \
             and inactive is not None:
                 break
         else:
-            raise RuntimeError("line(s) not found")
+            # we might get here when dealing with exotic Linux flavors, see:
+            # http://code.google.com/p/psutil/issues/detail?id=313
+            msg = "'cached', 'active' and 'inactive' memory stats couldn't " \
+                  "be determined and were set to 0"
+            warnings.warn(msg, RuntimeWarning)
+            cached = active = inactive = 0
     finally:
         f.close()
     avail = free + buffers + cached
     used = total - free
     percent = usage_percent((total - avail), total, _round=1)
     return nt_virtmem_info(total, avail, percent, used, free,
                            active, inactive, buffers, cached)
 
@@ -157,17 +176,22 @@ def swap_memory():
             # values are expressed in 4 kilo bytes, we want bytes instead
             if line.startswith('pswpin'):
                 sin = int(line.split(' ')[1]) * 4 * 1024
             elif line.startswith('pswpout'):
                 sout = int(line.split(' ')[1])  * 4 * 1024
             if sin is not None and sout is not None:
                 break
         else:
-            raise RuntimeError("line(s) not found")
+            # we might get here when dealing with exotic Linux flavors, see:
+            # http://code.google.com/p/psutil/issues/detail?id=313
+            msg = "'sin' and 'sout' swap memory stats couldn't " \
+                  "be determined and were set to 0"
+            warnings.warn(msg, RuntimeWarning)
+            sin = sout = 0
     finally:
         f.close()
     return nt_swapmeminfo(total, used, free, percent, sin, sout)
 
 # --- XXX deprecated memory functions
 
 @deprecated('psutil.virtual_memory().cached')
 def cached_phymem():
@@ -175,44 +199,75 @@ def cached_phymem():
 
 @deprecated('psutil.virtual_memory().buffers')
 def phymem_buffers():
     return virtual_memory().buffers
 
 
 # --- system CPU functions
 
+@memoize
+def _get_cputimes_ntuple():
+    """ Return a (nt, rindex) tuple depending on the CPU times available
+    on this Linux kernel version which may be:
+    user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]
+    """
+    f = open('/proc/stat', 'r')
+    try:
+        values = f.readline().split()[1:]
+    finally:
+        f.close()
+    fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
+    rindex = 8
+    vlen = len(values)
+    if vlen >= 8:
+        # Linux >= 2.6.11
+        fields.append('steal')
+        rindex += 1
+    if vlen >= 9:
+        # Linux >= 2.6.24
+        fields.append('guest')
+        rindex += 1
+    if vlen >= 10:
+        # Linux >= 3.2.0
+        fields.append('guest_nice')
+        rindex += 1
+    return (namedtuple('cputimes', ' '.join(fields)), rindex)
+
 def get_system_cpu_times():
-    """Return a named tuple representing the following CPU times:
-    user, nice, system, idle, iowait, irq, softirq.
+    """Return a named tuple representing the following system-wide
+    CPU times:
+    user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]
+    Last 3 fields may not be available on all Linux kernel versions.
     """
     f = open('/proc/stat', 'r')
     try:
         values = f.readline().split()
     finally:
         f.close()
-
-    values = values[1:8]
-    values = tuple([float(x) / _CLOCK_TICKS for x in values])
-    return nt_sys_cputimes(*values[:7])
+    nt, rindex = _get_cputimes_ntuple()
+    fields = values[1:rindex]
+    fields = [float(x) / _CLOCK_TICKS for x in fields]
+    return nt(*fields)
 
 def get_system_per_cpu_times():
     """Return a list of namedtuple representing the CPU times
     for every CPU available on the system.
     """
+    nt, rindex = _get_cputimes_ntuple()
     cpus = []
     f = open('/proc/stat', 'r')
-    # get rid of the first line who refers to system wide CPU stats
     try:
+        # get rid of the first line which refers to system wide CPU stats
         f.readline()
-        for line in f.readlines():
+        for line in f:
             if line.startswith('cpu'):
-                values = line.split()[1:8]
-                values = tuple([float(x) / _CLOCK_TICKS for x in values])
-                entry = nt_sys_cputimes(*values[:7])
+                fields = line.split()[1:rindex]
+                fields = [float(x) / _CLOCK_TICKS for x in fields]
+                entry = nt(*fields)
                 cpus.append(entry)
         return cpus
     finally:
         f.close()
 
 
 # --- system disk functions
 
@@ -246,17 +301,17 @@ get_disk_usage = _psposix.get_disk_usage
 # --- other sysetm functions
 
 def get_system_users():
     """Return currently connected users as a list of namedtuples."""
     retlist = []
     rawlist = _psutil_linux.get_system_users()
     for item in rawlist:
         user, tty, hostname, tstamp, user_process = item
-        # XXX the underlying C function includes entries about
+        # note: the underlying C function includes entries about
         # system boot, run level and others.  We might want
         # to use them in the future.
         if not user_process:
             continue
         if hostname == ':0.0':
             hostname = 'localhost'
         nt = nt_user(user, tty or None, hostname, tstamp)
         retlist.append(nt)
@@ -312,37 +367,44 @@ def disk_io_counters():
 
     # determine partitions we want to look for
     partitions = []
     f = open("/proc/partitions", "r")
     try:
         lines = f.readlines()[2:]
     finally:
         f.close()
-    for line in lines:
+    for line in reversed(lines):
         _, _, _, name = line.split()
         if name[-1].isdigit():
+            # we're dealing with a partition (e.g. 'sda1'); 'sda' will
+            # also be around but we want to omit it
             partitions.append(name)
+        else:
+            if not partitions or not partitions[-1].startswith(name):
+                # we're dealing with a disk entity for which no
+                # partitions have been defined (e.g. 'sda' but
+                # 'sda1' was not around), see:
+                # http://code.google.com/p/psutil/issues/detail?id=338
+                partitions.append(name)
     #
     retdict = {}
     f = open("/proc/diskstats", "r")
     try:
         lines = f.readlines()
     finally:
         f.close()
     for line in lines:
         _, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \
             line.split()[:11]
         if name in partitions:
             rbytes = int(rbytes) * SECTOR_SIZE
             wbytes = int(wbytes) * SECTOR_SIZE
             reads = int(reads)
             writes = int(writes)
-            # TODO: times are expressed in milliseconds while OSX/BSD has
-            # these expressed in nanoseconds; figure this out.
             rtime = int(rtime)
             wtime = int(wtime)
             retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime)
     return retdict
 
 
 # taken from /fs/proc/array.c
 _status_map = {"R" : STATUS_RUNNING,
@@ -353,23 +415,24 @@ def disk_io_counters():
                "Z" : STATUS_ZOMBIE,
                "X" : STATUS_DEAD,
                "x" : STATUS_DEAD,
                "K" : STATUS_WAKE_KILL,
                "W" : STATUS_WAKING}
 
 # --- decorators
 
-def wrap_exceptions(callable):
-    """Call callable into a try/except clause and translate ENOENT,
-    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError and IOError exceptions
+    into NoSuchProcess and AccessDenied.
     """
+    @wraps(fun)
     def wrapper(self, *args, **kwargs):
         try:
-            return callable(self, *args, **kwargs)
+            return fun(self, *args, **kwargs)
         except EnvironmentError:
             # ENOENT (no such file or directory) gets raised on open().
             # ESRCH (no such process) can get raised on read() if
             # process is gone in meantime.
             err = sys.exc_info()[1]
             if err.errno in (errno.ENOENT, errno.ESRCH):
                 raise NoSuchProcess(self.pid, self._process_name)
             if err.errno in (errno.EPERM, errno.EACCES):
@@ -379,18 +442,16 @@ def wrap_exceptions(callable):
 
 
 class Process(object):
     """Linux process implementation."""
 
     __slots__ = ["pid", "_process_name"]
 
     def __init__(self, pid):
-        if not isinstance(pid, int):
-            raise TypeError('pid must be an integer')
         self.pid = pid
         self._process_name = None
 
     @wrap_exceptions
     def get_process_name(self):
         f = open("/proc/%s/stat" % self.pid)
         try:
             name = f.read().split(' ')[1].replace('(', '').replace(')', '')
@@ -435,23 +496,24 @@ class Process(object):
         try:
             # return the args as a list
             return [x for x in f.read().split('\x00') if x]
         finally:
             f.close()
 
     @wrap_exceptions
     def get_process_terminal(self):
+        tmap = _psposix._get_terminal_map()
         f = open("/proc/%s/stat" % self.pid)
         try:
             tty_nr = int(f.read().split(' ')[6])
         finally:
             f.close()
         try:
-            return _TERMINAL_MAP[tty_nr]
+            return tmap[tty_nr]
         except KeyError:
             return None
 
     @wrap_exceptions
     def get_process_io_counters(self):
         f = open("/proc/%s/io" % self.pid)
         try:
             for line in f:
@@ -464,17 +526,18 @@ class Process(object):
                 elif line.startswith("write_bytes"):
                     write_bytes = int(line.split()[1])
             return nt_io(read_count, write_count, read_bytes, write_bytes)
         finally:
             f.close()
 
     if not os.path.exists('/proc/%s/io' % os.getpid()):
         def get_process_io_counters(self):
-            raise NotImplementedError('/proc/PID/io is not available')
+            raise NotImplementedError("couldn't find /proc/%s/io (kernel " \
+                                      "too old?)" % self.pid)
 
     @wrap_exceptions
     def get_cpu_times(self):
         f = open("/proc/%s/stat" % self.pid)
         try:
             st = f.read().strip()
         finally:
             f.close()
@@ -578,23 +641,25 @@ class Process(object):
                     except ValueError:
                         addr, perms, offset, dev, inode, path = hfields + ['']
                     if not path:
                         path = '[anon]'
                     else:
                         path = path.strip()
                     yield (addr, perms, path,
                            data['Rss:'],
-                           data['Size:'],
+                           data.get('Size:', 0),
                            data.get('Pss:', 0),
-                           data['Shared_Clean:'], data['Shared_Clean:'],
-                           data['Private_Clean:'], data['Private_Dirty:'],
-                           data['Referenced:'],
-                           data['Anonymous:'],
-                           data['Swap:'])
+                           data.get('Shared_Clean:', 0),
+                           data.get('Shared_Dirty:', 0),
+                           data.get('Private_Clean:', 0),
+                           data.get('Private_Dirty:', 0),
+                           data.get('Referenced:', 0),
+                           data.get('Anonymous:', 0),
+                           data.get('Swap:', 0))
             f.close()
         except EnvironmentError:
             # XXX - Can't use wrap_exceptions decorator as we're
             # returning a generator;  this probably needs some
             # refactoring in order to avoid this code duplication.
             if f is not None:
                 f.close()
             err = sys.exc_info()[1]
@@ -602,22 +667,22 @@ class Process(object):
                 raise NoSuchProcess(self.pid, self._process_name)
             if err.errno in (errno.EPERM, errno.EACCES):
                 raise AccessDenied(self.pid, self._process_name)
             raise
         except:
             if f is not None:
                 f.close()
             raise
+        f.close()
 
     if not os.path.exists('/proc/%s/smaps' % os.getpid()):
         def get_shared_libs(self, ext):
-            msg = "this Linux version does not support /proc/PID/smaps " \
-                  "(kernel < 2.6.14 or CONFIG_MMU kernel configuration " \
-                  "option is not enabled)"
+            msg = "couldn't find /proc/%s/smaps; kernel < 2.6.14 or CONFIG_MMU " \
+                  "kernel configuration option is not enabled" % self.pid
             raise NotImplementedError(msg)
 
     @wrap_exceptions
     def get_process_cwd(self):
         # readlink() might return paths containing null bytes causing
         # problems when used with other fs-related functions (os.*,
         # open(), ...)
         path = os.readlink("/proc/%s/cwd" % self.pid)
@@ -630,28 +695,31 @@ class Process(object):
         try:
             for line in f:
                 if line.startswith("voluntary_ctxt_switches"):
                     vol = int(line.split()[1])
                 elif line.startswith("nonvoluntary_ctxt_switches"):
                     unvol = int(line.split()[1])
                 if vol is not None and unvol is not None:
                     return nt_ctxsw(vol, unvol)
-            raise RuntimeError("line not found")
+            raise NotImplementedError("the 'voluntary_ctxt_switches' and " \
+                "'nonvoluntary_ctxt_switches' fields were not found in " \
+                "/proc/%s/status; the kernel is probably older than 2.6.23" \
+                % self.pid)
         finally:
             f.close()
 
     @wrap_exceptions
     def get_process_num_threads(self):
         f = open("/proc/%s/status" % self.pid)
         try:
             for line in f:
                 if line.startswith("Threads:"):
                     return int(line.split()[1])
-            raise RuntimeError("line not found")
+            raise NotImplementedError("line not found")
         finally:
             f.close()
 
     @wrap_exceptions
     def get_process_threads(self):
         thread_ids = os.listdir("/proc/%s/task" % self.pid)
         thread_ids.sort()
         retlist = []
@@ -931,41 +999,41 @@ class Process(object):
     @wrap_exceptions
     def get_process_ppid(self):
         f = open("/proc/%s/status" % self.pid)
         try:
             for line in f:
                 if line.startswith("PPid:"):
                     # PPid: nnnn
                     return int(line.split()[1])
-            raise RuntimeError("line not found")
+            raise NotImplementedError("line not found")
         finally:
             f.close()
 
     @wrap_exceptions
     def get_process_uids(self):
         f = open("/proc/%s/status" % self.pid)
         try:
             for line in f:
                 if line.startswith('Uid:'):
                     _, real, effective, saved, fs = line.split()
                     return nt_uids(int(real), int(effective), int(saved))
-            raise RuntimeError("line not found")
+            raise NotImplementedError("line not found")
         finally:
             f.close()
 
     @wrap_exceptions
     def get_process_gids(self):
         f = open("/proc/%s/status" % self.pid)
         try:
             for line in f:
                 if line.startswith('Gid:'):
                     _, real, effective, saved, fs = line.split()
                     return nt_gids(int(real), int(effective), int(saved))
-            raise RuntimeError("line not found")
+            raise NotImplementedError("line not found")
         finally:
             f.close()
 
     @staticmethod
     def _decode_address(addr, family):
         """Accept an "ip:port" address as displayed in /proc/net/*
         and convert it into a human readable form, like:
 
--- a/python/psutil/psutil/_psmswindows.py
+++ b/python/psutil/psutil/_psmswindows.py
@@ -1,40 +1,56 @@
 #!/usr/bin/env python
-#
-# $Id: _psmswindows.py 1514 2012-08-14 11:16:56Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Windows platform implementation."""
 
 import errno
 import os
 import sys
 import platform
+import warnings
 
 import _psutil_mswindows
 from _psutil_mswindows import ERROR_ACCESS_DENIED
-from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
+from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
 from psutil._common import *
-from psutil._compat import PY3, xrange, long
+from psutil._compat import PY3, xrange, long, wraps
 
 # Windows specific extended namespace
 __extra__all__ = ["ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
                   "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
                   "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS"]
 
 
 # --- module level constants (gets pushed up to psutil module)
 
-NUM_CPUS = _psutil_mswindows.get_num_cpus()
-BOOT_TIME = _psutil_mswindows.get_system_uptime()
-TOTAL_PHYMEM = _psutil_mswindows.get_virtual_mem()[0]
+# Since these constants get determined at import time we do not want to
+# crash immediately; instead we'll set them to None and most likely
+# we'll crash later as they're used for determining process CPU stats
+# and creation_time
+try:
+    NUM_CPUS = _psutil_mswindows.get_num_cpus()
+except Exception:
+    NUM_CPUS = None
+    warnings.warn("couldn't determine platform's NUM_CPUS", RuntimeWarning)
+try:
+    BOOT_TIME = _psutil_mswindows.get_system_boot_time()
+except Exception:
+    BOOT_TIME = None
+    warnings.warn("couldn't determine platform's BOOT_TIME", RuntimeWarning)
+try:
+    TOTAL_PHYMEM = _psutil_mswindows.get_virtual_mem()[0]
+except Exception:
+    TOTAL_PHYMEM = None
+    warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
+
 WAIT_TIMEOUT = 0x00000102 # 258 in decimal
 ACCESS_DENIED_SET = frozenset([errno.EPERM, errno.EACCES, ERROR_ACCESS_DENIED])
 
 # process priority constants:
 # http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
 from _psutil_mswindows import (ABOVE_NORMAL_PRIORITY_CLASS,
                                BELOW_NORMAL_PRIORITY_CLASS,
                                HIGH_PRIORITY_CLASS,
@@ -55,16 +71,18 @@ def _convert_raw_path(s):
         s = s.decode('utf8')
     rawdrive = '\\'.join(s.split('\\')[:3])
     driveletter = _win32_QueryDosDevice(rawdrive)
     return os.path.join(driveletter, s[len(rawdrive):])
 
 
 # --- public functions
 
+get_system_boot_time = _psutil_mswindows.get_system_boot_time
+
 nt_virtmem_info = namedtuple('vmem', ' '.join([
     # all platforms
     'total', 'available', 'percent', 'used', 'free']))
 
 def virtual_memory():
     """System virtual memory as a namedtuple."""
     mem = _psutil_mswindows.get_virtual_mem()
     totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem
@@ -137,24 +155,24 @@ def get_system_users():
 
 get_pid_list = _psutil_mswindows.get_pid_list
 pid_exists = _psutil_mswindows.pid_exists
 network_io_counters = _psutil_mswindows.get_network_io_counters
 disk_io_counters = _psutil_mswindows.get_disk_io_counters
 
 # --- decorator
 
-def wrap_exceptions(callable):
-    """Call callable into a try/except clause so that if a
-    WindowsError 5 AccessDenied exception is raised we translate it
-    into psutil.AccessDenied
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError and WindowsError
+    exceptions into NoSuchProcess and AccessDenied.
     """
+    @wraps(fun)
     def wrapper(self, *args, **kwargs):
         try:
-            return callable(self, *args, **kwargs)
+            return fun(self, *args, **kwargs)
         except OSError:
             err = sys.exc_info()[1]
             if err.errno in ACCESS_DENIED_SET:
                 raise AccessDenied(self.pid, self._process_name)
             if err.errno == errno.ESRCH:
                 raise NoSuchProcess(self.pid, self._process_name)
             raise
     return wrapper
@@ -354,16 +372,32 @@ class Process(object):
     @wrap_exceptions
     def get_process_nice(self):
         return _psutil_mswindows.get_process_priority(self.pid)
 
     @wrap_exceptions
     def set_process_nice(self, value):
         return _psutil_mswindows.set_process_priority(self.pid, value)
 
+    # available on Windows >= Vista
+    if hasattr(_psutil_mswindows, "get_process_io_priority"):
+        @wrap_exceptions
+        def get_process_ionice(self):
+            return _psutil_mswindows.get_process_io_priority(self.pid)
+
+        @wrap_exceptions
+        def set_process_ionice(self, value, _):
+            if _:
+                raise TypeError("set_process_ionice() on Windows takes only " \
+                                "1 argument (2 given)")
+            if value not in (2, 1, 0):
+                raise ValueError("value must be 2 (normal), 1 (low) or 0 " \
+                                 "(very low); got %r" % value)
+            return _psutil_mswindows.set_process_io_priority(self.pid, value)
+
     @wrap_exceptions
     def get_process_io_counters(self):
         try:
             ret = _psutil_mswindows.get_process_io_counters(self.pid)
         except OSError:
             err = sys.exc_info()[1]
             if err.errno in ACCESS_DENIED_SET:
                 ret = _psutil_mswindows.get_process_io_counters_2(self.pid)
@@ -387,28 +421,26 @@ class Process(object):
 
     @wrap_exceptions
     def set_process_cpu_affinity(self, value):
         def to_bitmask(l):
             if not l:
                 raise ValueError("invalid argument %r" % l)
             out = 0
             for b in l:
-                if not isinstance(b, (int, long)) or b < 0:
-                    raise ValueError("invalid argument %r" % b)
                 out |= 2**b
             return out
 
         # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
         # is returned for an invalid CPU but this seems not to be true,
         # therefore we check CPUs validy beforehand.
         allcpus = list(range(len(get_system_per_cpu_times())))
         for cpu in value:
             if cpu not in allcpus:
-                raise ValueError("invalid CPU %i" % cpu)
+                raise ValueError("invalid CPU %r" % cpu)
 
         bitmask = to_bitmask(value)
         _psutil_mswindows.set_process_cpu_affinity(self.pid, bitmask)
 
     @wrap_exceptions
     def get_num_handles(self):
         try:
             return _psutil_mswindows.get_process_num_handles(self.pid)
--- a/python/psutil/psutil/_psosx.py
+++ b/python/psutil/psutil/_psosx.py
@@ -1,42 +1,59 @@
 #!/usr/bin/env python
-#
-# $Id: _psosx.py 1498 2012-07-24 21:41:28Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """OSX platform implementation."""
 
 import errno
 import os
 import sys
+import warnings
 
 import _psutil_osx
 import _psutil_posix
 from psutil import _psposix
-from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
-from psutil._compat import namedtuple
+from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
+from psutil._compat import namedtuple, wraps
 from psutil._common import *
 
 __extra__all__ = []
 
 # --- constants
 
-NUM_CPUS = _psutil_osx.get_num_cpus()
-BOOT_TIME = _psutil_osx.get_system_boot_time()
-TOTAL_PHYMEM = _psutil_osx.get_virtual_mem()[0]
+# Since these constants get determined at import time we do not want to
+# crash immediately; instead we'll set them to None and most likely
+# we'll crash later as they're used for determining process CPU stats
+# and creation_time
+try:
+    NUM_CPUS = _psutil_osx.get_num_cpus()
+except Exception:
+    NUM_CPUS = None
+    warnings.warn("couldn't determine platform's NUM_CPUS", RuntimeWarning)
+try:
+    BOOT_TIME = _psutil_osx.get_system_boot_time()
+except Exception:
+    BOOT_TIME = None
+    warnings.warn("couldn't determine platform's BOOT_TIME", RuntimeWarning)
+try:
+    TOTAL_PHYMEM = _psutil_osx.get_virtual_mem()[0]
+except Exception:
+    TOTAL_PHYMEM = None
+    warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
+
 _PAGESIZE = os.sysconf("SC_PAGE_SIZE")
-_TERMINAL_MAP = _psposix._get_terminal_map()
 _cputimes_ntuple = namedtuple('cputimes', 'user nice system idle')
 
 # --- functions
 
+get_system_boot_time = _psutil_osx.get_system_boot_time
+
 nt_virtmem_info = namedtuple('vmem', ' '.join([
     # all platforms
     'total', 'available', 'percent', 'used', 'free',
     # OSX specific
     'active',
     'inactive',
     'wired']))
 
@@ -101,24 +118,24 @@ def get_system_users():
 get_pid_list = _psutil_osx.get_pid_list
 pid_exists = _psposix.pid_exists
 get_disk_usage = _psposix.get_disk_usage
 network_io_counters = _psutil_osx.get_network_io_counters
 disk_io_counters = _psutil_osx.get_disk_io_counters
 
 # --- decorator
 
-def wrap_exceptions(callable):
-    """Call callable into a try/except clause so that if an
-    OSError EPERM exception is raised we translate it into
-    psutil.AccessDenied.
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError exceptions into
+    NoSuchProcess and AccessDenied.
     """
+    @wraps(fun)
     def wrapper(self, *args, **kwargs):
         try:
-            return callable(self, *args, **kwargs)
+            return fun(self, *args, **kwargs)
         except OSError:
             err = sys.exc_info()[1]
             if err.errno == errno.ESRCH:
                 raise NoSuchProcess(self.pid, self._process_name)
             if err.errno in (errno.EPERM, errno.EACCES):
                 raise AccessDenied(self.pid, self._process_name)
             raise
     return wrapper
@@ -174,18 +191,19 @@ class Process(object):
     @wrap_exceptions
     def get_process_gids(self):
         real, effective, saved = _psutil_osx.get_process_gids(self.pid)
         return nt_gids(real, effective, saved)
 
     @wrap_exceptions
     def get_process_terminal(self):
         tty_nr = _psutil_osx.get_process_tty_nr(self.pid)
+        tmap = _psposix._get_terminal_map()
         try:
-            return _TERMINAL_MAP[tty_nr]
+            return tmap[tty_nr]
         except KeyError:
             return None
 
     @wrap_exceptions
     def get_memory_info(self):
         """Return a tuple with the process' RSS and VMS size."""
         rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2]
         return nt_meminfo(rss, vms)
--- a/python/psutil/psutil/_psposix.py
+++ b/python/psutil/psutil/_psposix.py
@@ -1,33 +1,29 @@
 #!/usr/bin/env python
-#
-# $Id: _psposix.py 1409 2012-07-04 08:21:06Z g.rodola $
-#
+
 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Routines common to all posix systems."""
 
 import os
 import errno
 import psutil
 import sys
 import time
 import glob
 
-from psutil.error import TimeoutExpired
-from psutil._common import nt_diskinfo, usage_percent
+from psutil._error import TimeoutExpired
+from psutil._common import nt_diskinfo, usage_percent, memoize
 
 
 def pid_exists(pid):
     """Check whether pid exists in the current process table."""
-    if not isinstance(pid, int):
-        raise TypeError('an integer is required')
     if pid < 0:
         return False
     try:
         os.kill(pid, 0)
     except OSError:
         e = sys.exc_info()[1]
         return e.errno == errno.EPERM
     else:
@@ -41,24 +37,25 @@ def wait_pid(pid, timeout=None):
     waits until the process disappears and return None.
 
     If pid does not exist at all return None immediately.
 
     Raise TimeoutExpired on timeout expired.
     """
     def check_timeout(delay):
         if timeout is not None:
-            if time.time() >= stop_at:
+            if timer() >= stop_at:
                 raise TimeoutExpired(pid)
         time.sleep(delay)
         return min(delay * 2, 0.04)
 
+    timer = getattr(time, 'monotonic', time.time)
     if timeout is not None:
         waitcall = lambda: os.waitpid(pid, os.WNOHANG)
-        stop_at = time.time() + timeout
+        stop_at = timer() + timeout
     else:
         waitcall = lambda: os.waitpid(pid, 0)
 
     delay = 0.0001
     while 1:
         try:
             retpid, status = waitcall()
         except OSError:
@@ -104,15 +101,21 @@ def get_disk_usage(path):
     total = (st.f_blocks * st.f_frsize)
     used = (st.f_blocks - st.f_bfree) * st.f_frsize
     percent = usage_percent(used, total, _round=1)
     # NB: the percentage is -5% than what shown by df due to
     # reserved blocks that we are currently not considering:
     # http://goo.gl/sWGbH
     return nt_diskinfo(total, used, free, percent)
 
+@memoize
 def _get_terminal_map():
     ret = {}
     ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
     for name in ls:
         assert name not in ret
-        ret[os.stat(name).st_rdev] = name
+        try:
+            ret[os.stat(name).st_rdev] = name
+        except OSError:
+            err = sys.exc_info()[1]
+            if err.errno != errno.ENOENT:
+                raise
     return ret
--- a/python/psutil/psutil/_psutil_bsd.c
+++ b/python/psutil/psutil/_psutil_bsd.c
@@ -1,47 +1,41 @@
 /*
- * $Id: _psutil_bsd.c 1513 2012-08-14 11:01:37Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * FreeBSD platform-specific module methods for _psutil_bsd
  */
 
+
 #include <Python.h>
 #include <assert.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <signal.h>
 #include <fcntl.h>
+#include <paths.h>
 #include <sys/types.h>
 #include <sys/sysctl.h>
 #include <sys/param.h>
 #include <sys/user.h>
 #include <sys/proc.h>
 #include <sys/file.h>
 #include <net/route.h>
 
 #include <sys/socket.h>
-#include <sys/socketvar.h>    /* for struct socket */
-#include <sys/protosw.h>      /* for struct proto */
-#include <sys/domain.h>       /* for struct domain */
-
-#include <sys/un.h>           /* for unpcb struct (UNIX sockets) */
-#include <sys/unpcb.h>        /* for unpcb struct (UNIX sockets) */
-#include <sys/mbuf.h>         /* for mbuf struct (UNIX sockets) */
-/* for in_pcb struct */
+#include <sys/socketvar.h>    /* for struct xsocket */
+/* for xinpcb struct */
 #include <netinet/in.h>
 #include <netinet/in_systm.h>
 #include <netinet/ip.h>
 #include <netinet/in_pcb.h>
-#include <netinet/tcp_var.h>   /* for struct tcpcb */
+#include <netinet/tcp_var.h>   /* for struct xtcpcb */
 #include <netinet/tcp_fsm.h>   /* for TCP connection states */
 #include <arpa/inet.h>         /* for inet_ntop() */
 
 #if __FreeBSD_version < 900000
     #include <utmp.h>         /* system users */
 #else
     #include <utmpx.h>
 #endif
@@ -65,17 +59,17 @@
 // convert a timeval struct to a double
 #define TV2DOUBLE(t)    ((t).tv_sec + (t).tv_usec / 1000000.0)
 
 
 /*
  * Utility function which fills a kinfo_proc struct based on process pid
  */
 static int
-get_kinfo_proc(const pid_t pid, struct kinfo_proc *proc)
+psutil_get_kinfo_proc(const pid_t pid, struct kinfo_proc *proc)
 {
     int mib[4];
     size_t size;
     mib[0] = CTL_KERN;
     mib[1] = KERN_PROC;
     mib[2] = KERN_PROC_PID;
     mib[3] = pid;
 
@@ -105,17 +99,20 @@ get_pid_list(PyObject* self, PyObject* a
 {
     kinfo_proc *proclist = NULL;
     kinfo_proc *orig_address = NULL;
     size_t num_processes;
     size_t idx;
     PyObject* retlist = PyList_New(0);
     PyObject* pid = NULL;
 
-    if (get_proc_list(&proclist, &num_processes) != 0) {
+    if (retlist == NULL) {
+        return NULL;
+    }
+    if (psutil_get_proc_list(&proclist, &num_processes) != 0) {
         PyErr_SetString(PyExc_RuntimeError, "failed to retrieve process list.");
         goto error;
     }
 
     if (num_processes > 0) {
         orig_address = proclist; // save so we can free it after we're done
         for (idx=0; idx < num_processes; idx++) {
             pid = Py_BuildValue("i", proclist->ki_pid);
@@ -145,41 +142,39 @@ error:
  * Return a Python float indicating the system boot time expressed in
  * seconds since the epoch.
  */
 static PyObject*
 get_system_boot_time(PyObject* self, PyObject* args)
 {
     /* fetch sysctl "kern.boottime" */
     static int request[2] = { CTL_KERN, KERN_BOOTTIME };
-    struct timeval result;
-    size_t result_len = sizeof result;
-    time_t boot_time = 0;
+    struct timeval boottime;
+    size_t len = sizeof(boottime);
 
-    if (sysctl(request, 2, &result, &result_len, NULL, 0) == -1) {
+    if (sysctl(request, 2, &boottime, &len, NULL, 0) == -1) {
         PyErr_SetFromErrno(0);
         return NULL;
     }
-    boot_time = result.tv_sec;
-    return Py_BuildValue("f", (float)boot_time);
+    return Py_BuildValue("d", (double)boottime.tv_sec);
 }
 
 
 /*
  * Return process name from kinfo_proc as a Python string.
  */
 static PyObject*
 get_process_name(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("s", kp.ki_comm);
 }
 
 
 /*
  * Return process pathname executable.
@@ -193,33 +188,36 @@ get_process_exe(PyObject* self, PyObject
     char pathname[PATH_MAX];
     int error;
     int mib[4];
     size_t size;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (pid == 0) {
-        // ...otherwise we'd get '\x98\xd5\xbf\xbf\xfb\xf3\x10\x08H\x01'
-        return Py_BuildValue("s", "");
-    }
 
     mib[0] = CTL_KERN;
     mib[1] = KERN_PROC;
     mib[2] = KERN_PROC_PATHNAME;
     mib[3] = pid;
 
     size = sizeof(pathname);
     error = sysctl(mib, 4, pathname, &size, NULL, 0);
     if (error == -1) {
         PyErr_SetFromErrno(PyExc_OSError);
         return NULL;
     }
-
+    if (size == 0 || strlen(pathname) == 0) {
+        if (psutil_pid_exists(pid) == 0) {
+            return NoSuchProcess();
+        }
+        else {
+            strcpy(pathname, "");
+        }
+    }
     return Py_BuildValue("s", pathname);
 }
 
 
 /*
  * Return process cmdline as a Python list of cmdline arguments.
  */
 static PyObject*
@@ -228,19 +226,19 @@ get_process_cmdline(PyObject* self, PyOb
     long pid;
     PyObject* arglist = NULL;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
 
     // get the commandline, defined in arch/bsd/process_info.c
-    arglist = get_arg_list(pid);
+    arglist = psutil_get_arg_list(pid);
 
-    // get_arg_list() returns NULL only if getcmdargs failed with ESRCH
+    // psutil_get_arg_list() returns NULL only if psutil_get_cmd_args failed with ESRCH
     // (no process with that PID)
     if (NULL == arglist) {
         return PyErr_SetFromErrno(PyExc_OSError);
     }
     return Py_BuildValue("N", arglist);
 }
 
 
@@ -250,17 +248,17 @@ get_process_cmdline(PyObject* self, PyOb
 static PyObject*
 get_process_ppid(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("l", (long)kp.ki_ppid);
 }
 
 
 /*
  * Return process status as a Python integer.
@@ -268,17 +266,17 @@ get_process_ppid(PyObject* self, PyObjec
 static PyObject*
 get_process_status(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("i", (int)kp.ki_stat);
 }
 
 
 /*
  * Return process real, effective and saved user ids from kinfo_proc
@@ -287,17 +285,17 @@ get_process_status(PyObject* self, PyObj
 static PyObject*
 get_process_uids(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("lll", (long)kp.ki_ruid,
                                 (long)kp.ki_uid,
                                 (long)kp.ki_svuid);
 }
 
 
@@ -308,17 +306,17 @@ get_process_uids(PyObject* self, PyObjec
 static PyObject*
 get_process_gids(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("lll", (long)kp.ki_rgid,
                                 (long)kp.ki_groups[0],
                                 (long)kp.ki_svuid);
 }
 
 
@@ -329,17 +327,17 @@ get_process_gids(PyObject* self, PyObjec
 static PyObject*
 get_process_tty_nr(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("i", kp.ki_tdev);
 }
 
 
 /*
  * Return the number of context switches performed by process as a tuple.
@@ -347,17 +345,17 @@ get_process_tty_nr(PyObject* self, PyObj
 static PyObject*
 get_process_num_ctx_switches(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("(ll)", kp.ki_rusage.ru_nvcsw,
                                  kp.ki_rusage.ru_nivcsw);
 }
 
 
 
@@ -367,17 +365,17 @@ get_process_num_ctx_switches(PyObject* s
 static PyObject*
 get_process_num_threads(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("l", (long)kp.ki_numthreads);
 }
 
 
 /*
  * Retrieves all threads used by process returning a list of tuples
@@ -393,19 +391,20 @@ get_process_threads(PyObject* self, PyOb
     struct kinfo_proc *kip = NULL;
     struct kinfo_proc *kipp;
     int error;
     unsigned int i;
     size_t size;
     PyObject* retList = PyList_New(0);
     PyObject* pyTuple = NULL;
 
-    if (! PyArg_ParseTuple(args, "l", &pid)) {
+    if (retList == NULL)
+        return NULL;
+    if (! PyArg_ParseTuple(args, "l", &pid))
         goto error;
-    }
 
     /*
      * We need to re-query for thread information, so don't use *kipp.
      */
     mib[0] = CTL_KERN;
     mib[1] = KERN_PROC;
     mib[2] = KERN_PROC_PID | KERN_PROC_INC_THREAD;
     mib[3] = pid;
@@ -418,17 +417,17 @@ get_process_threads(PyObject* self, PyOb
     }
     if (size == 0) {
         NoSuchProcess();
         goto error;
     }
 
     kip = malloc(size);
     if (kip == NULL) {
-        PyErr_SetFromErrno(PyExc_OSError);
+        PyErr_NoMemory();
         goto error;
     }
 
     error = sysctl(mib, 4, kip, &size, NULL, 0);
     if (error == -1) {
         PyErr_SetFromErrno(PyExc_OSError);
         goto error;
     }
@@ -469,17 +468,17 @@ static PyObject*
 get_process_cpu_times(PyObject* self, PyObject* args)
 {
     long pid;
     double user_t, sys_t;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     // convert from microseconds to seconds
     user_t = TV2DOUBLE(kp.ki_rusage.ru_utime);
     sys_t = TV2DOUBLE(kp.ki_rusage.ru_stime);
     return Py_BuildValue("(dd)", user_t, sys_t);
 }
 
@@ -514,17 +513,17 @@ get_num_cpus(PyObject* self, PyObject* a
 static PyObject*
 get_process_create_time(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("d", TV2DOUBLE(kp.ki_start));
 }
 
 
 /*
  * Return a Python float indicating the process create time expressed in
@@ -533,17 +532,17 @@ get_process_create_time(PyObject* self, 
 static PyObject*
 get_process_io_counters(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     // there's apparently no way to determine bytes count, hence return -1.
     return Py_BuildValue("(llll)", kp.ki_rusage.ru_inblock,
                                    kp.ki_rusage.ru_oublock,
                                    -1, -1);
 }
 
@@ -554,52 +553,58 @@ get_process_io_counters(PyObject* self, 
 static PyObject*
 get_process_memory_info(PyObject* self, PyObject* args)
 {
     long pid;
     struct kinfo_proc kp;
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         return NULL;
     }
     return Py_BuildValue("(lllll)", ptoa(kp.ki_rssize),    // rss
                                     (long)kp.ki_size,      // vms
                                     ptoa(kp.ki_tsize),     // text
                                     ptoa(kp.ki_dsize),     // data
                                     ptoa(kp.ki_ssize));    // stack
 }
 
 
 /*
  * Return virtual memory usage statistics.
  */
 static PyObject*
 get_virtual_mem(PyObject* self, PyObject* args)
 {
-    unsigned int   total, active, inactive, wired, cached, free, buffers;
-    size_t		   size = sizeof(total);
-	struct vmtotal vm;
-	int            mib[] = {CTL_VM, VM_METER};
-	long           pagesize = getpagesize();
+    unsigned int   total, active, inactive, wired, cached, free;
+    size_t         size = sizeof(total);
+    struct vmtotal vm;
+    int            mib[] = {CTL_VM, VM_METER};
+    long           pagesize = getpagesize();
+#if __FreeBSD_version > 702101
+    long buffers;
+#else
+    int buffers;
+#endif
+    size_t buffers_size = sizeof(buffers);
 
     if (sysctlbyname("vm.stats.vm.v_page_count", &total, &size, NULL, 0))
         goto error;
     if (sysctlbyname("vm.stats.vm.v_active_count", &active, &size, NULL, 0))
         goto error;
     if (sysctlbyname("vm.stats.vm.v_inactive_count", &inactive, &size, NULL, 0))
         goto error;
     if (sysctlbyname("vm.stats.vm.v_wire_count", &wired, &size, NULL, 0))
         goto error;
     if (sysctlbyname("vm.stats.vm.v_cache_count", &cached, &size, NULL, 0))
         goto error;
     if (sysctlbyname("vm.stats.vm.v_free_count", &free, &size, NULL, 0))
         goto error;
-    if (sysctlbyname("vfs.bufspace", &buffers, &size, NULL, 0))
+    if (sysctlbyname("vfs.bufspace", &buffers, &buffers_size, NULL, 0))
         goto error;
 
     size = sizeof(vm);
     if (sysctl(mib, 2, &vm, &size, NULL, 0) != 0)
         goto error;
 
     return Py_BuildValue("KKKKKKKK",
         (unsigned long long) total    * pagesize,
@@ -613,32 +618,45 @@ get_virtual_mem(PyObject* self, PyObject
     );
 
 error:
     PyErr_SetFromErrno(0);
     return NULL;
 }
 
 
+#ifndef _PATH_DEVNULL
+#define _PATH_DEVNULL "/dev/null"
+#endif
+
 /*
  * Return swap memory stats (see 'swapinfo' cmdline tool)
  */
 static PyObject*
 get_swap_mem(PyObject* self, PyObject* args)
 {
     kvm_t *kd;
     struct kvm_swap kvmsw[1];
     unsigned int swapin, swapout, nodein, nodeout;
     size_t size = sizeof(unsigned int);
 
+    kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open failed");
+    if (kd == NULL) {
+        PyErr_SetString(PyExc_RuntimeError, "kvm_open failed");
+        return NULL;
+    }
+
     if (kvm_getswapinfo(kd, kvmsw, 1, 0) < 0) {
+        kvm_close(kd);
         PyErr_SetString(PyExc_RuntimeError, "kvm_getswapinfo failed");
         return NULL;
     }
 
+    kvm_close(kd);
+
     if (sysctlbyname("vm.stats.vm.v_swapin", &swapin, &size, NULL, 0) == -1)
         goto sbn_error;
     if (sysctlbyname("vm.stats.vm.v_swapout", &swapout, &size, NULL, 0) == -1)
         goto sbn_error;
     if (sysctlbyname("vm.stats.vm.v_vnodein", &nodein, &size, NULL, 0) == -1)
         goto sbn_error;
     if (sysctlbyname("vm.stats.vm.v_vnodeout", &nodeout, &size, NULL, 0) == -1)
         goto sbn_error;
@@ -693,31 +711,32 @@ get_system_cpu_times(PyObject* self, PyO
 /*
  * Return files opened by process as a list of (path, fd) tuples
  */
 static PyObject*
 get_process_open_files(PyObject* self, PyObject* args)
 {
     long pid;
     int i, cnt;
+    struct kinfo_file *freep = NULL;
+    struct kinfo_file *kif;
+    struct kinfo_proc kipp;
     PyObject *retList = PyList_New(0);
     PyObject *tuple = NULL;
 
-    struct kinfo_file *freep = NULL;
-    struct kinfo_file *kif;
-    struct kinfo_proc kipp;
-
+    if (retList == NULL)
+        return NULL;
     if (! PyArg_ParseTuple(args, "l", &pid))
         goto error;
-    if (get_kinfo_proc(pid, &kipp) == -1)
+    if (psutil_get_kinfo_proc(pid, &kipp) == -1)
         goto error;
 
     freep = kinfo_getfile(pid, &cnt);
     if (freep == NULL) {
-        PyErr_SetFromErrno(0);
+        psutil_raise_ad_or_nsp(pid);
         goto error;
     }
 
     for (i = 0; i < cnt; i++) {
         kif = &freep[i];
         if ((kif->kf_type == KF_TYPE_VNODE) &&
             (kif->kf_vnode_type == KF_VTYPE_VREG))
         {
@@ -750,22 +769,22 @@ get_process_num_fds(PyObject* self, PyOb
     long pid;
     int cnt;
 
     struct kinfo_file *freep;
     struct kinfo_proc kipp;
 
     if (! PyArg_ParseTuple(args, "l", &pid))
         return NULL;
-    if (get_kinfo_proc(pid, &kipp) == -1)
+    if (psutil_get_kinfo_proc(pid, &kipp) == -1)
         return NULL;
 
     freep = kinfo_getfile(pid, &cnt);
     if (freep == NULL) {
-        PyErr_SetFromErrno(0);
+        psutil_raise_ad_or_nsp(pid);
         return NULL;
     }
     free(freep);
 
     return Py_BuildValue("i", cnt);
 }
 
 
@@ -780,22 +799,22 @@ get_process_cwd(PyObject* self, PyObject
     struct kinfo_file *freep = NULL;
     struct kinfo_file *kif;
     struct kinfo_proc kipp;
 
     int i, cnt;
 
     if (! PyArg_ParseTuple(args, "l", &pid))
         goto error;
-    if (get_kinfo_proc(pid, &kipp) == -1)
+    if (psutil_get_kinfo_proc(pid, &kipp) == -1)
         goto error;
 
     freep = kinfo_getfile(pid, &cnt);
     if (freep == NULL) {
-        PyErr_SetFromErrno(0);
+        psutil_raise_ad_or_nsp(pid);
         goto error;
     }
 
     for (i = 0; i < cnt; i++) {
         kif = &freep[i];
         if (kif->kf_fd == KF_FD_TYPE_CWD) {
             path = Py_BuildValue("s", kif->kf_path);
             if (!path)
@@ -851,281 +870,296 @@ get_connection_status(int st) {
             return "LAST_ACK";
         case TCPS_TIME_WAIT:
             return "TIME_WAIT";
         default:
             return "?";
     }
 }
 
-// a kvm_read that returns true if everything is read
-#define KVM_READ(kaddr, paddr, len) \
-    ((len) < SSIZE_MAX && \
-    kvm_read(kd, (u_long)(kaddr), (char *)(paddr), (len)) == (ssize_t)(len))
+/* The tcplist fetching and walking is borrowed from netstat/inet.c. */
+static char *
+psutil_fetch_tcplist(void)
+{
+    char *buf;
+    size_t len;
+    int error;
+
+    for (;;) {
+        if (sysctlbyname("net.inet.tcp.pcblist", NULL, &len, NULL, 0) < 0) {
+            PyErr_SetFromErrno(0);
+            return NULL;
+        }
+        buf = malloc(len);
+        if (buf == NULL) {
+            PyErr_NoMemory();
+            return NULL;
+        }
+        if (sysctlbyname("net.inet.tcp.pcblist", buf, &len, NULL, 0) < 0) {
+            free(buf);
+            PyErr_SetFromErrno(0);
+            return NULL;
+        }
+        return buf;
+    }
+}
+
+static int
+psutil_sockaddr_port(int family, struct sockaddr_storage *ss)
+{
+    struct sockaddr_in6 *sin6;
+    struct sockaddr_in *sin;
+
+    if (family == AF_INET) {
+        sin = (struct sockaddr_in *)ss;
+        return (sin->sin_port);
+    } else {
+        sin6 = (struct sockaddr_in6 *)ss;
+        return (sin6->sin6_port);
+    }
+}
+
+static void *
+psutil_sockaddr_addr(int family, struct sockaddr_storage *ss)
+{
+    struct sockaddr_in6 *sin6;
+    struct sockaddr_in *sin;
+
+    if (family == AF_INET) {
+        sin = (struct sockaddr_in *)ss;
+        return (&sin->sin_addr);
+    } else {
+        sin6 = (struct sockaddr_in6 *)ss;
+        return (&sin6->sin6_addr);
+    }
+}
 
-// XXX - copied from sys/file.h to make compiler happy
-struct file {
-    void        *f_data;    /* file descriptor specific data */
-    struct fileops  *f_ops;     /* File operations */
-    struct ucred    *f_cred;    /* associated credentials. */
-    struct vnode    *f_vnode;   /* NULL or applicable vnode */
-    short       f_type;     /* descriptor type */
-    short       f_vnread_flags; /* (f) Sleep lock for f_offset */
-    volatile u_int  f_flag;     /* see fcntl.h */
-    volatile u_int  f_count;    /* reference count */
-    int     f_seqcount; /* Count of sequential accesses. */
-    off_t       f_nextoff;  /* next expected read/write offset. */
-    struct cdev_privdata *f_cdevpriv; /* (d) Private data for the cdev. */
-    off_t       f_offset;
-    void        *f_label;   /* Place-holder for MAC label. */
-};
+static socklen_t
+psutil_sockaddr_addrlen(int family)
+{
+    if (family == AF_INET)
+        return (sizeof(struct in_addr));
+    else
+        return (sizeof(struct in6_addr));
+}
+
+static int
+psutil_sockaddr_matches(int family, int port, void *pcb_addr,
+                        struct sockaddr_storage *ss)
+{
+    if (psutil_sockaddr_port(family, ss) != port)
+        return (0);
+    return (memcmp(psutil_sockaddr_addr(family, ss), pcb_addr,
+        psutil_sockaddr_addrlen(family)) == 0);
+}
+
+static struct tcpcb *
+psutil_search_tcplist(char *buf, struct kinfo_file *kif)
+{
+    struct tcpcb *tp;
+    struct inpcb *inp;
+    struct xinpgen *xig, *oxig;
+    struct xsocket *so;
 
+    oxig = xig = (struct xinpgen *)buf;
+    for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
+         xig->xig_len > sizeof(struct xinpgen);
+         xig = (struct xinpgen *)((char *)xig + xig->xig_len)) {
+        tp = &((struct xtcpcb *)xig)->xt_tp;
+        inp = &((struct xtcpcb *)xig)->xt_inp;
+        so = &((struct xtcpcb *)xig)->xt_socket;
+
+        if (so->so_type != kif->kf_sock_type ||
+            so->xso_family != kif->kf_sock_domain ||
+            so->xso_protocol != kif->kf_sock_protocol)
+                continue;
+
+        if (kif->kf_sock_domain == AF_INET) {
+            if (!psutil_sockaddr_matches(AF_INET, inp->inp_lport, &inp->inp_laddr,
+                &kif->kf_sa_local))
+                continue;
+            if (!psutil_sockaddr_matches(AF_INET, inp->inp_fport, &inp->inp_faddr,
+                &kif->kf_sa_peer))
+                continue;
+        } else {
+            if (!psutil_sockaddr_matches(AF_INET6, inp->inp_lport, &inp->in6p_laddr,
+                &kif->kf_sa_local))
+                continue;
+            if (!psutil_sockaddr_matches(AF_INET6, inp->inp_fport, &inp->in6p_faddr,
+                &kif->kf_sa_peer))
+                continue;
+        }
+
+        return (tp);
+    }
+    return NULL;
+}
 
 /*
  * Return connections opened by process.
- * fstat.c source code was used as an example.
  */
 static PyObject*
 get_process_connections(PyObject* self, PyObject* args)
 {
     long pid;
-    struct kinfo_proc *p;
-    struct file **ofiles = NULL;
-    char buf[_POSIX2_LINE_MAX];
-    char path[PATH_MAX];
-    int cnt;
-    int i;
-    kvm_t *kd = NULL;
-    struct file file;
-    struct filedesc filed;
-    struct nlist nl[] = {{ "" },};
-    struct socket   so;
-    struct protosw  proto;
-    struct domain   dom;
-    struct inpcb    inpcb;
-    struct tcpcb    tcpcb;
-    struct unpcb    unpcb;
+    int i, cnt;
+
+    struct kinfo_file *freep = NULL;
+    struct kinfo_file *kif;
+    struct kinfo_proc kipp;
+    char *tcplist = NULL;
+    struct tcpcb *tcp;
 
     PyObject *retList = PyList_New(0);
     PyObject *tuple = NULL;
     PyObject *laddr = NULL;
     PyObject *raddr = NULL;
     PyObject *af_filter = NULL;
     PyObject *type_filter = NULL;
     PyObject* _family = NULL;
     PyObject* _type = NULL;
 
+    if (retList == NULL) {
+        return NULL;
+    }
     if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter)) {
         goto error;
     }
     if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
         PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
         goto error;
     }
 
-    kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, buf);
-    if (kd == NULL) {
-        AccessDenied();
+    if (psutil_get_kinfo_proc(pid, &kipp) == -1) {
         goto error;
     }
 
-    if (kvm_nlist(kd, nl) != 0) {
-        PyErr_SetString(PyExc_RuntimeError, "kvm_nlist() failed");
+    freep = kinfo_getfile(pid, &cnt);
+    if (freep == NULL) {
+        psutil_raise_ad_or_nsp(pid);
         goto error;
     }
 
-    p = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
-    if (p == NULL) {
-        NoSuchProcess();
-        goto error;
-    }
-    if (cnt != 1) {
-        NoSuchProcess();
-        goto error;
-    }
-    if (p->ki_fd == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "no usable fd found");
-        goto error;
-    }
-    if (!KVM_READ(p->ki_fd, &filed, sizeof(filed))) {
-        PyErr_SetString(PyExc_RuntimeError, "kvm_read() failed");
+    tcplist = psutil_fetch_tcplist();
+    if (tcplist == NULL) {
+        PyErr_SetFromErrno(0);
         goto error;
     }
 
-    ofiles = malloc((filed.fd_lastfile+1) * sizeof(struct file *));
-    if (ofiles == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "malloc() failed");
-        goto error;
-    }
-
-    if (!KVM_READ(filed.fd_ofiles, ofiles,
-                  (filed.fd_lastfile+1) * sizeof(struct file *))) {
-        PyErr_SetString(PyExc_RuntimeError, "kvm_read() failed");
-        goto error;
-    }
-
-    for (i = 0; i <= filed.fd_lastfile; i++) {
+    for (i = 0; i < cnt; i++) {
         int lport, rport;
         char lip[200], rip[200];
+        char path[PATH_MAX];
         char *state;
         int inseq;
         tuple = NULL;
         laddr = NULL;
         raddr = NULL;
 
-        if (ofiles[i] == NULL) {
-            continue;
-        }
-        if (!KVM_READ(ofiles[i], &file, sizeof (struct file))) {
-            PyErr_SetString(PyExc_RuntimeError, "kvm_read() file failed");
-            goto error;
-        }
-        if (file.f_type == DTYPE_SOCKET) {
-            // fill in socket
-            if (!KVM_READ(file.f_data, &so, sizeof(struct socket))) {
-                PyErr_SetString(PyExc_RuntimeError, "kvm_read() socket failed");
-                goto error;
-            }
-            // fill in protosw entry
-            if (!KVM_READ(so.so_proto, &proto, sizeof(struct protosw))) {
-                PyErr_SetString(PyExc_RuntimeError, "kvm_read() proto failed");
-                goto error;
-            }
-            // fill in domain
-            if (!KVM_READ(proto.pr_domain, &dom, sizeof(struct domain))) {
-                PyErr_SetString(PyExc_RuntimeError, "kvm_read() domain failed");
-                goto error;
-            }
-
+        kif = &freep[i];
+        if (kif->kf_type == KF_TYPE_SOCKET)
+        {
             // apply filters
-            _family = PyLong_FromLong((long)dom.dom_family);
+            _family = PyLong_FromLong((long)kif->kf_sock_domain);
             inseq = PySequence_Contains(af_filter, _family);
             Py_DECREF(_family);
             if (inseq == 0) {
                 continue;
             }
-            _type = PyLong_FromLong((long)proto.pr_type);
+            _type = PyLong_FromLong((long)kif->kf_sock_type);
             inseq = PySequence_Contains(type_filter, _type);
             Py_DECREF(_type);
             if (inseq == 0) {
                 continue;
             }
 
             // IPv4 / IPv6 socket
-            if ((dom.dom_family == AF_INET) || (dom.dom_family == AF_INET6)) {
-                // fill inpcb
-                if (kvm_read(kd, (u_long)so.so_pcb, (char *)&inpcb,
-                             sizeof(struct inpcb)) != sizeof(struct inpcb)) {
-                    PyErr_SetString(PyExc_RuntimeError, "kvm_read() addr failed");
-                    goto error;
-                }
-
+            if ((kif->kf_sock_domain == AF_INET) ||
+                (kif->kf_sock_domain == AF_INET6)) {
                 // fill status
-                if (proto.pr_type == SOCK_STREAM) {
-                    if (kvm_read(kd, (u_long)inpcb.inp_ppcb, (char *)&tcpcb,
-                                 sizeof(struct tcpcb)) != sizeof(struct tcpcb)) {
-                        PyErr_SetString(PyExc_RuntimeError, "kvm_read() state failed");
-                        goto error;
-                    }
-                    state = get_connection_status((int)tcpcb.t_state);
-                }
-                else {
-                    state = "";
+                state = "";
+                if (kif->kf_sock_type == SOCK_STREAM) {
+                    tcp = psutil_search_tcplist(tcplist, kif);
+                    if (tcp != NULL)
+                        state = get_connection_status((int)tcp->t_state);
                 }
 
                 // build addr and port
-                if (dom.dom_family == AF_INET) {
-                    inet_ntop(AF_INET, &inpcb.inp_laddr.s_addr, lip, sizeof(lip));
-                    inet_ntop(AF_INET, &inpcb.inp_faddr.s_addr, rip, sizeof(rip));
-                }
-                else {
-                    inet_ntop(AF_INET6, &inpcb.in6p_laddr.s6_addr, lip, sizeof(lip));
-                    inet_ntop(AF_INET6, &inpcb.in6p_faddr.s6_addr, rip, sizeof(rip));
-                }
-                lport = ntohs(inpcb.inp_lport);
-                rport = ntohs(inpcb.inp_fport);
+                inet_ntop(kif->kf_sock_domain,
+                    psutil_sockaddr_addr(kif->kf_sock_domain, &kif->kf_sa_local),
+                    lip, sizeof(lip));
+                inet_ntop(kif->kf_sock_domain,
+                    psutil_sockaddr_addr(kif->kf_sock_domain, &kif->kf_sa_peer),
+                    rip, sizeof(rip));
+                lport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
+                                                   &kif->kf_sa_local));
+                rport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
+                                                   &kif->kf_sa_peer));
 
-                // contruct python tuple/list
+                // construct python tuple/list
                 laddr = Py_BuildValue("(si)", lip, lport);
                 if (!laddr)
                     goto error;
                 if (rport != 0) {
                     raddr = Py_BuildValue("(si)", rip, rport);
                 }
                 else {
                     raddr = Py_BuildValue("()");
                 }
                 if (!raddr)
                     goto error;
-                tuple = Py_BuildValue("(iiiNNs)", i,
-                                                  dom.dom_family,
-                                                  proto.pr_type,
+                tuple = Py_BuildValue("(iiiNNs)", kif->kf_fd,
+                                                  kif->kf_sock_domain,
+                                                  kif->kf_sock_type,
                                                   laddr,
                                                   raddr,
                                                   state);
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
                     goto error;
                 Py_DECREF(tuple);
             }
             // UNIX socket
-            else if (dom.dom_family == AF_UNIX) {
-                struct sockaddr_un sun;
-                path[0] = '\0';
+            else if (kif->kf_sock_domain == AF_UNIX) {
+                struct sockaddr_un *sun;
 
-                if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
-                             sizeof(struct unpcb)) != sizeof(struct unpcb)) {
-                    PyErr_SetString(PyExc_RuntimeError, "kvm_read() unpcb failed");
-                    goto error;
-                }
-                if (unpcb.unp_addr) {
-                    if (kvm_read(kd, (u_long)unpcb.unp_addr, (char *)&sun,
-                                 sizeof(sun)) != sizeof(sun)) {
-                        PyErr_SetString(PyExc_RuntimeError,
-                                        "kvm_read() sockaddr_un failed");
-                        goto error;
-                    }
-                    sprintf(path, "%.*s",
-                            (sun.sun_len - (sizeof(sun) - sizeof(sun.sun_path))),
-                             sun.sun_path);
-                }
+                sun = (struct sockaddr_un *)&kif->kf_sa_local;
+                snprintf(path, sizeof(path), "%.*s",
+                        (sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
+                         sun->sun_path);
 
-                tuple = Py_BuildValue("(iiisOs)", i,
-                                                  dom.dom_family,
-                                                  proto.pr_type,
+                tuple = Py_BuildValue("(iiisOs)", kif->kf_fd,
+                                                  kif->kf_sock_domain,
+                                                  kif->kf_sock_type,
                                                   path,
                                                   Py_None,
                                                   "");
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
                     goto error;
                 Py_DECREF(tuple);
                 Py_INCREF(Py_None);
             }
         }
     }
-
-    free(ofiles);
-    kvm_close(kd);
+    free(freep);
+    free(tcplist);
     return retList;
 
 error:
     Py_XDECREF(tuple);
     Py_XDECREF(laddr);
     Py_XDECREF(raddr);
     Py_DECREF(retList);
-
-    if (kd != NULL) {
-        kvm_close(kd);
-    }
-    if (ofiles != NULL) {
-        free(ofiles);
-    }
+    if (freep != NULL)
+        free(freep);
+    if (tcplist != NULL)
+        free(tcplist);
     return NULL;
 }
 
 
 /*
  * Return a Python list of tuple representing per-cpu times
  */
 static PyObject*
@@ -1135,16 +1169,19 @@ get_system_per_cpu_times(PyObject* self,
     int mib[2];
     int ncpu;
     size_t len;
     size_t size;
     int i;
     PyObject* py_retlist = PyList_New(0);
     PyObject* py_cputime = NULL;
 
+    if (py_retlist == NULL)
+        return NULL;
+
     // retrieve maxcpus value
     size = sizeof(maxcpus);
     if (sysctlbyname("kern.smp.maxcpus", &maxcpus, &size, NULL, 0) < 0) {
         Py_DECREF(py_retlist);
         PyErr_SetFromErrno(0);
         return NULL;
     }
     long cpu_time[maxcpus][CPUSTATES];
@@ -1184,63 +1221,77 @@ get_system_per_cpu_times(PyObject* self,
 
 error:
     Py_XDECREF(py_cputime);
     Py_DECREF(py_retlist);
     return NULL;
 }
 
 
+// remove spaces from string
+void remove_spaces(char *str) {
+    char *p1 = str;
+    char *p2 = str;
+    do
+        while (*p2 == ' ')
+            p2++;
+    while (*p1++ = *p2++);
+}
+
 /*
  * Return a list of tuples for every process memory maps.
  * 'procstat' cmdline utility has been used as an example.
  */
 static PyObject*
 get_process_memory_maps(PyObject* self, PyObject* args)
 {
     long pid;
     int ptrwidth;
     int i, cnt;
     char addr[30];
-    char perms[10];
+    char perms[4];
     const char *path;
     struct kinfo_proc kp;
     struct kinfo_vmentry *freep = NULL;
     struct kinfo_vmentry *kve;
+    ptrwidth = 2*sizeof(void *);
     PyObject* pytuple = NULL;
     PyObject* retlist = PyList_New(0);
 
-    ptrwidth = 2*sizeof(void *);
-
+    if (retlist == NULL) {
+        return NULL;
+    }
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         goto error;
     }
-    if (get_kinfo_proc(pid, &kp) == -1) {
+    if (psutil_get_kinfo_proc(pid, &kp) == -1) {
         goto error;
     }
 
     freep = kinfo_getvmmap(pid, &cnt);
     if (freep == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "kinfo_getvmmap() failed");
+        psutil_raise_ad_or_nsp(pid);
         goto error;
     }
     for (i = 0; i < cnt; i++) {
         pytuple = NULL;
         kve = &freep[i];
         addr[0] = '\0';
         perms[0] = '\0';
         sprintf(addr, "%#*jx-%#*jx", ptrwidth, (uintmax_t)kve->kve_start,
                                      ptrwidth, (uintmax_t)kve->kve_end);
+        remove_spaces(addr);
         strlcat(perms, kve->kve_protection & KVME_PROT_READ ? "r" : "-",
                 sizeof(perms));
         strlcat(perms, kve->kve_protection & KVME_PROT_WRITE ? "w" : "-",
                 sizeof(perms));
         strlcat(perms, kve->kve_protection & KVME_PROT_EXEC ? "x" : "-",
                 sizeof(perms));
 
+
         if (strlen(kve->kve_path) == 0) {
             switch (kve->kve_type) {
             case KVME_TYPE_NONE:
                 path = "[none]";
                 break;
             case KVME_TYPE_DEFAULT:
                 path = "[default]";
                 break;
@@ -1313,27 +1364,34 @@ get_disk_partitions(PyObject* self, PyOb
     int i;
     long len;
     uint64_t flags;
     char opts[200];
     struct statfs *fs = NULL;
     PyObject* py_retlist = PyList_New(0);
     PyObject* py_tuple = NULL;
 
+    if (py_retlist == NULL)
+        return NULL;
+
     // get the number of mount points
     Py_BEGIN_ALLOW_THREADS
     num = getfsstat(NULL, 0, MNT_NOWAIT);
     Py_END_ALLOW_THREADS
     if (num == -1) {
         PyErr_SetFromErrno(0);
         goto error;
     }
 
     len = sizeof(*fs) * num;
     fs = malloc(len);
+    if (fs == NULL) {
+        PyErr_NoMemory();
+        goto error;
+    }
 
     Py_BEGIN_ALLOW_THREADS
     num = getfsstat(fs, len, MNT_NOWAIT);
     Py_END_ALLOW_THREADS
     if (num == -1) {
         PyErr_SetFromErrno(0);
         goto error;
     }
@@ -1403,38 +1461,42 @@ error:
 
 
 /*
  * Return a Python list of named tuples with overall network I/O information
  */
 static PyObject*
 get_network_io_counters(PyObject* self, PyObject* args)
 {
-    PyObject* py_retdict = PyDict_New();
-    PyObject* py_ifc_info = NULL;
-
     char *buf = NULL, *lim, *next;
     struct if_msghdr *ifm;
     int mib[6];
     size_t len;
+    PyObject* py_retdict = PyDict_New();
+    PyObject* py_ifc_info = NULL;
+    if (py_retdict == NULL)
+        return NULL;
 
     mib[0] = CTL_NET;          // networking subsystem
     mib[1] = PF_ROUTE;         // type of information
     mib[2] = 0;                // protocol (IPPROTO_xxx)
     mib[3] = 0;                // address family
     mib[4] = NET_RT_IFLIST;   // operation
     mib[5] = 0;
 
     if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
         PyErr_SetFromErrno(0);
         goto error;
     }
 
-
     buf = malloc(len);
+    if (buf == NULL) {
+        PyErr_NoMemory();
+        goto error;
+    }
 
     if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
         PyErr_SetFromErrno(0);
         goto error;
     }
 
     lim = buf + len;
 
@@ -1445,16 +1507,22 @@ get_network_io_counters(PyObject* self, 
 
         if (ifm->ifm_type == RTM_IFINFO) {
             struct if_msghdr *if2m = (struct if_msghdr *)ifm;
             struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
             char ifc_name[32];
 
             strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
             ifc_name[sdl->sdl_nlen] = 0;
+            // XXX: ignore usbus interfaces:
+            // http://lists.freebsd.org/pipermail/freebsd-current/2011-October/028752.html
+            // 'ifconfig -a' doesn't show them, nor do we.
+            if (strncmp(ifc_name, "usbus", 5) == 0) {
+                continue;
+            }
 
             py_ifc_info = Py_BuildValue("(kkkkkkki)",
                                         if2m->ifm_data.ifi_obytes,
                                         if2m->ifm_data.ifi_ibytes,
                                         if2m->ifm_data.ifi_opackets,
                                         if2m->ifm_data.ifi_ipackets,
                                         if2m->ifm_data.ifi_ierrors,
                                         if2m->ifm_data.ifi_oerrors,
@@ -1484,28 +1552,34 @@ error:
 
 
 /*
  * Return a Python dict of tuples for disk I/O information
  */
 static PyObject*
 get_disk_io_counters(PyObject* self, PyObject* args)
 {
+    int i;
+    struct statinfo stats;
+
     PyObject* py_retdict = PyDict_New();
     PyObject* py_disk_info = NULL;
-
-    int i;
-    struct statinfo stats;
+    if (py_retdict == NULL)
+        return NULL;
 
     if (devstat_checkversion(NULL) < 0) {
         PyErr_Format(PyExc_RuntimeError, "devstat_checkversion() failed");
         goto error;
     }
 
     stats.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
+    if (stats.dinfo == NULL) {
+        PyErr_NoMemory();
+        goto error;
+    }
     bzero(stats.dinfo, sizeof(struct devinfo));
 
     if (devstat_getdevs(NULL, &stats) == -1) {
         PyErr_Format(PyExc_RuntimeError, "devstat_getdevs() failed");
         goto error;
     }
 
     for (i = 0; i < stats.dinfo->numdevs; i++) {
@@ -1553,16 +1627,19 @@ error:
  * Return currently connected users as a list of tuples.
  */
 static PyObject*
 get_system_users(PyObject* self, PyObject* args)
 {
     PyObject *ret_list = PyList_New(0);
     PyObject *tuple = NULL;
 
+    if (ret_list == NULL)
+        return NULL;
+
 #if __FreeBSD_version < 900000
     struct utmp ut;
     FILE *fp;
 
     fp = fopen(_PATH_UTMP, "r");
     if (fp == NULL) {
         PyErr_SetFromErrno(0);
         goto error;
@@ -1687,18 +1764,17 @@ PsutilMethods[] =
          "Return swap mem stats"},
      {"get_system_cpu_times", get_system_cpu_times, METH_VARARGS,
          "Return system cpu times as a tuple (user, system, nice, idle, irc)"},
 #if defined(__FreeBSD_version) && __FreeBSD_version >= 800000
      {"get_system_per_cpu_times", get_system_per_cpu_times, METH_VARARGS,
          "Return system per-cpu times as a list of tuples"},
 #endif
      {"get_system_boot_time", get_system_boot_time, METH_VARARGS,
-         "Return a float indicating the system boot time expressed in "
-         "seconds since the epoch"},
+         "Return the system boot time expressed in seconds since the epoch."},
      {"get_disk_partitions", get_disk_partitions, METH_VARARGS,
          "Return a list of tuples including device, mount point and "
          "fs type for all partitions mounted on the system."},
      {"get_network_io_counters", get_network_io_counters, METH_VARARGS,
          "Return dict of tuples of networks I/O information."},
      {"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
          "Return a Python dict of tuples for disk I/O information"},
      {"get_system_users", get_system_users, METH_VARARGS,
--- a/python/psutil/psutil/_psutil_bsd.h
+++ b/python/psutil/psutil/_psutil_bsd.h
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_bsd.h 1498 2012-07-24 21:41:28Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * BSD platform-specific module methods for _psutil_bsd
  */
 
 #include <Python.h>
--- a/python/psutil/psutil/_psutil_common.c
+++ b/python/psutil/psutil/_psutil_common.c
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_common.c 1142 2011-10-05 18:45:49Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Routines common to all platforms.
  */
 
 #include <Python.h>
@@ -31,9 +29,8 @@ PyObject *
 AccessDenied(void) {
     PyObject *exc;
     char *msg = strerror(EACCES);
     exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg);
     PyErr_SetObject(PyExc_OSError, exc);
     Py_XDECREF(exc);
     return NULL;
 }
-
--- a/python/psutil/psutil/_psutil_common.h
+++ b/python/psutil/psutil/_psutil_common.h
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_common.h 1142 2011-10-05 18:45:49Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  */
 
 #include <Python.h>
 
 PyObject* NoSuchProcess(void);
--- a/python/psutil/psutil/_psutil_linux.c
+++ b/python/psutil/psutil/_psutil_linux.c
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_linux.c 1498 2012-07-24 21:41:28Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Linux-specific functions.
  */
 
 #include <Python.h>
@@ -102,16 +100,19 @@ linux_ioprio_set(PyObject* self, PyObjec
 static PyObject*
 get_disk_partitions(PyObject* self, PyObject* args)
 {
     FILE *file = NULL;
     struct mntent *entry;
     PyObject* py_retlist = PyList_New(0);
     PyObject* py_tuple = NULL;
 
+    if (py_retlist == NULL)
+        return NULL;
+
     // MOUNTED constant comes from mntent.h and it's == '/etc/mtab'
     Py_BEGIN_ALLOW_THREADS
     file = setmntent(MOUNTED, "r");
     Py_END_ALLOW_THREADS
     if ((file == 0) || (file == NULL)) {
         PyErr_SetFromErrno(PyExc_OSError);
         goto error;
     }
@@ -148,24 +149,25 @@ error:
  */
 static PyObject*
 get_sysinfo(PyObject* self, PyObject* args)
 {
     struct sysinfo info;
     if (sysinfo(&info) != 0) {
         return PyErr_SetFromErrno(PyExc_OSError);
     }
+
+    // note: BOOT_TIME might also be determined from here
     return Py_BuildValue("(KKKKKK)",
         (unsigned long long)info.totalram  * info.mem_unit,   // total
         (unsigned long long)info.freeram   * info.mem_unit,   // free
         (unsigned long long)info.bufferram * info.mem_unit,   // buffer
         (unsigned long long)info.sharedram * info.mem_unit,   // shared
         (unsigned long long)info.totalswap * info.mem_unit,   // swap tot
         (unsigned long long)info.freeswap  * info.mem_unit);  // swap free
-    // TODO: we can also determine BOOT_TIME here
 }
 
 
 /*
  * Return process CPU affinity as a Python long (the bitmask)
  */
 static PyObject*
 get_process_cpu_affinity(PyObject* self, PyObject* args)
@@ -211,16 +213,19 @@ set_process_cpu_affinity(PyObject* self,
 static PyObject*
 get_system_users(PyObject* self, PyObject* args)
 {
     PyObject *ret_list = PyList_New(0);
     PyObject *tuple = NULL;
     PyObject *user_proc = NULL;
     struct utmp *ut;
 
+    if (ret_list == NULL)
+        return NULL;
+
     setutent();
     while (NULL != (ut = getutent())) {
         tuple = NULL;
         user_proc = NULL;
         if (ut->ut_type == USER_PROCESS)
             user_proc = Py_True;
         else
             user_proc = Py_False;
--- a/python/psutil/psutil/_psutil_linux.h
+++ b/python/psutil/psutil/_psutil_linux.h
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_linux.h 1498 2012-07-24 21:41:28Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * LINUX specific module methods for _psutil_linux
  */
 
 #include <Python.h>
--- a/python/psutil/psutil/_psutil_mswindows.c
+++ b/python/psutil/psutil/_psutil_mswindows.c
@@ -1,11 +1,9 @@
 /*
- * $Id: _psutil_mswindows.c 1525 2012-08-16 16:32:03Z g.rodola $
- *
  * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Windows platform-specific module methods for _psutil_mswindows
  */
 
 // Fixes clash between winsock2.h and windows.h
@@ -34,17 +32,17 @@
 #include "arch/mswindows/ntextapi.h"
 
 
 /*
  * Return a Python float representing the system uptime expressed in seconds
  * since the epoch.
  */
 static PyObject*
-get_system_uptime(PyObject* self, PyObject* args)
+get_system_boot_time(PyObject* self, PyObject* args)
 {
     double uptime;
     time_t pt;
     FILETIME fileTime;
     long long ll;
 
     GetSystemTimeAsFileTime(&fileTime);
 
@@ -79,19 +77,19 @@ pid_exists(PyObject* self, PyObject* arg
 {
     long pid;
     int status;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
 
-    status = pid_is_running(pid);
+    status = psutil_pid_is_running(pid);
     if (-1 == status) {
-        return NULL; // exception raised in pid_is_running()
+        return NULL; // exception raised in psutil_pid_is_running()
     }
     return PyBool_FromLong(status);
 }
 
 
 /*
  * Return a Python list of all the PIDs running on the system.
  */
@@ -99,17 +97,20 @@ static PyObject*
 get_pid_list(PyObject* self, PyObject* args)
 {
     DWORD *proclist = NULL;
     DWORD numberOfReturnedPIDs;
     DWORD i;
     PyObject* pid = NULL;
     PyObject* retlist = PyList_New(0);
 
-    proclist = get_pids(&numberOfReturnedPIDs);
+    if (retlist == NULL) {
+        return NULL;
+    }
+    proclist = psutil_get_pids(&numberOfReturnedPIDs);
     if (NULL == proclist) {
         goto error;
     }
 
     for (i = 0; i < numberOfReturnedPIDs; i++) {
         pid = Py_BuildValue("I", proclist[i]);
         if (!pid)
             goto error;
@@ -243,17 +244,17 @@ get_process_cpu_times(PyObject* self, Py
     long        pid;
     HANDLE      hProcess;
     FILETIME    ftCreate, ftExit, ftKernel, ftUser;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
 
-    hProcess = handle_from_pid(pid);
+    hProcess = psutil_handle_from_pid(pid);
     if (hProcess == NULL) {
         return NULL;
     }
 
     if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
         CloseHandle(hProcess);
         if (GetLastError() == ERROR_ACCESS_DENIED) {
             // usually means the process has died so we throw a NoSuchProcess
@@ -330,20 +331,20 @@ get_process_create_time(PyObject* self, 
     FILETIME    ftCreate, ftExit, ftKernel, ftUser;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
 
     // special case for PIDs 0 and 4, return BOOT_TIME
     if (0 == pid || 4 == pid) {
-        return get_system_uptime(NULL, NULL);
+        return get_system_boot_time(NULL, NULL);
     }
 
-    hProcess = handle_from_pid(pid);
+    hProcess = psutil_handle_from_pid(pid);
     if (hProcess == NULL) {
         return NULL;
     }
 
     if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
         CloseHandle(hProcess);
         if (GetLastError() == ERROR_ACCESS_DENIED) {
             // usually means the process has died so we throw a NoSuchProcess here
@@ -402,17 +403,17 @@ get_process_create_time_2(PyObject* self
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
     if (! get_process_info(pid, &am