Try using unowned ptr in CJX_Object

And clear it in CXFA_LayoutItem dtor.

Change-Id: I60ffeee18384f06edb0991912bb33d8d4f10c4d6
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/63871
Commit-Queue: Lei Zhang <thestig@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
diff --git a/fxjs/xfa/cjx_object.h b/fxjs/xfa/cjx_object.h
index 6394b28..09a0818 100644
--- a/fxjs/xfa/cjx_object.h
+++ b/fxjs/xfa/cjx_object.h
@@ -108,8 +108,8 @@
   void SetCalcRecursionCount(size_t count) { calc_recursion_count_ = count; }
   size_t GetCalcRecursionCount() const { return calc_recursion_count_; }
 
-  void SetLayoutItem(CXFA_LayoutItem* item) { layout_item_ = item; }
-  CXFA_LayoutItem* GetLayoutItem() const { return layout_item_; }
+  void SetLayoutItem(CXFA_LayoutItem* item) { layout_item_.Reset(item); }
+  CXFA_LayoutItem* GetLayoutItem() const { return layout_item_.Get(); }
 
   bool HasMethod(const WideString& func) const;
   CJS_Result RunMethod(const WideString& func,
@@ -258,13 +258,7 @@
   void MoveBufferMapData(CXFA_Object* pDstModule);
 
   UnownedPtr<CXFA_Object> object_;
-  // This is an UnownedPtr but, due to lifetime issues, can't be marked as such
-  // at this point. The CJX_Node is freed by its parent CXFA_Node. The CXFA_Node
-  // will be freed during CXFA_NodeHolder destruction (CXFA_Document
-  // destruction as the only implementation). This will happen after the
-  // CXFA_LayoutProcessor is destroyed in the CXFA_Document, leaving this as a
-  // bad unowned ptr.
-  CXFA_LayoutItem* layout_item_ = nullptr;
+  UnownedPtr<CXFA_LayoutItem> layout_item_;
   std::unique_ptr<XFA_MAPMODULEDATA> map_module_data_;
   std::unique_ptr<CXFA_CalcData> calc_data_;
   std::map<ByteString, CJX_MethodCall> method_specs_;
diff --git a/xfa/fxfa/layout/cxfa_layoutitem.cpp b/xfa/fxfa/layout/cxfa_layoutitem.cpp
index 9ee7b61..b4523c9 100644
--- a/xfa/fxfa/layout/cxfa_layoutitem.cpp
+++ b/xfa/fxfa/layout/cxfa_layoutitem.cpp
@@ -40,6 +40,11 @@
 
 CXFA_LayoutItem::~CXFA_LayoutItem() {
   CHECK(!GetParent());
+  if (m_pFormNode) {
+    auto* pJSObj = m_pFormNode->JSObject();
+    if (pJSObj && pJSObj->GetLayoutItem() == this)
+      pJSObj->SetLayoutItem(nullptr);
+  }
 }
 
 CXFA_ViewLayoutItem* CXFA_LayoutItem::AsViewLayoutItem() {