Add CPDF_Dictionary::GetMutableStream().

Change-Id: I026867d04a64f9cf4c91aec62c51f27dc65512bb
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/94710
Commit-Queue: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
diff --git a/core/fpdfapi/parser/cpdf_dictionary.cpp b/core/fpdfapi/parser/cpdf_dictionary.cpp
index 9c0eea5..236fbe2 100644
--- a/core/fpdfapi/parser/cpdf_dictionary.cpp
+++ b/core/fpdfapi/parser/cpdf_dictionary.cpp
@@ -178,8 +178,9 @@
   return ToStream(GetDirectObjectFor(key));
 }
 
-CPDF_Stream* CPDF_Dictionary::GetStreamFor(const ByteString& key) {
-  return ToStream(GetMutableDirectObjectFor(key)).Get();
+RetainPtr<CPDF_Stream> CPDF_Dictionary::GetMutableStreamFor(
+    const ByteString& key) {
+  return pdfium::WrapRetain(const_cast<CPDF_Stream*>(GetStreamFor(key)));
 }
 
 CFX_FloatRect CPDF_Dictionary::GetRectFor(const ByteString& key) const {
diff --git a/core/fpdfapi/parser/cpdf_dictionary.h b/core/fpdfapi/parser/cpdf_dictionary.h
index c868816..8d54406 100644
--- a/core/fpdfapi/parser/cpdf_dictionary.h
+++ b/core/fpdfapi/parser/cpdf_dictionary.h
@@ -73,7 +73,7 @@
   const CPDF_Array* GetArrayFor(const ByteString& key) const;
   RetainPtr<CPDF_Array> GetMutableArrayFor(const ByteString& key);
   const CPDF_Stream* GetStreamFor(const ByteString& key) const;
-  CPDF_Stream* GetStreamFor(const ByteString& key);
+  RetainPtr<CPDF_Stream> GetMutableStreamFor(const ByteString& key);
   CFX_FloatRect GetRectFor(const ByteString& key) const;
   CFX_Matrix GetMatrixFor(const ByteString& key) const;
 
diff --git a/core/fpdfapi/render/cpdf_renderstatus.cpp b/core/fpdfapi/render/cpdf_renderstatus.cpp
index 61f91ef..53b8bc9 100644
--- a/core/fpdfapi/render/cpdf_renderstatus.cpp
+++ b/core/fpdfapi/render/cpdf_renderstatus.cpp
@@ -1373,7 +1373,8 @@
   if (!pSMaskDict)
     return nullptr;
 
-  CPDF_Stream* pGroup = pSMaskDict->GetStreamFor(pdfium::transparency::kG);
+  RetainPtr<CPDF_Stream> pGroup =
+      pSMaskDict->GetMutableStreamFor(pdfium::transparency::kG);
   if (!pGroup)
     return nullptr;
 
@@ -1387,7 +1388,7 @@
   matrix.Translate(-pClipRect->left, -pClipRect->top);
 
   CPDF_Form form(m_pContext->GetDocument(), m_pContext->GetPageResources(),
-                 pGroup);
+                 pGroup.Get());
   form.ParseContent();
 
   CFX_DefaultRenderDevice bitmap_device;
diff --git a/core/fpdfdoc/cpdf_annot.cpp b/core/fpdfdoc/cpdf_annot.cpp
index 0165c9d..09f45bd 100644
--- a/core/fpdfdoc/cpdf_annot.cpp
+++ b/core/fpdfdoc/cpdf_annot.cpp
@@ -17,6 +17,7 @@
 #include "core/fpdfapi/parser/cpdf_boolean.h"
 #include "core/fpdfapi/parser/cpdf_dictionary.h"
 #include "core/fpdfapi/parser/cpdf_document.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfapi/parser/fpdf_parser_utility.h"
 #include "core/fpdfapi/render/cpdf_pagerendercache.h"
 #include "core/fpdfapi/render/cpdf_rendercontext.h"
@@ -56,9 +57,9 @@
   return pForm;
 }
 
-CPDF_Stream* GetAnnotAPInternal(CPDF_Dictionary* pAnnotDict,
-                                CPDF_Annot::AppearanceMode eMode,
-                                bool bFallbackToNormal) {
+RetainPtr<CPDF_Stream> GetAnnotAPInternal(CPDF_Dictionary* pAnnotDict,
+                                          CPDF_Annot::AppearanceMode eMode,
+                                          bool bFallbackToNormal) {
   RetainPtr<CPDF_Dictionary> pAP =
       pAnnotDict->GetMutableDictFor(pdfium::annotation::kAP);
   if (!pAP)
@@ -76,7 +77,8 @@
   if (!psub)
     return nullptr;
 
-  if (CPDF_Stream* pStream = psub->AsStream())
+  RetainPtr<CPDF_Stream> pStream(psub->AsStream());
+  if (pStream)
     return pStream;
 
   CPDF_Dictionary* pDict = psub->AsDictionary();
@@ -92,7 +94,7 @@
     }
     as = (!value.IsEmpty() && pDict->KeyExist(value)) ? value : "Off";
   }
-  return pDict->GetStreamFor(as);
+  return pDict->GetMutableStreamFor(as);
 }
 
 }  // namespace
@@ -171,20 +173,20 @@
   return !!(GetFlags() & pdfium::annotation_flags::kHidden);
 }
 
-CPDF_Stream* GetAnnotAP(CPDF_Dictionary* pAnnotDict,
-                        CPDF_Annot::AppearanceMode eMode) {
+RetainPtr<CPDF_Stream> GetAnnotAP(CPDF_Dictionary* pAnnotDict,
+                                  CPDF_Annot::AppearanceMode eMode) {
   DCHECK(pAnnotDict);
   return GetAnnotAPInternal(pAnnotDict, eMode, true);
 }
 
-CPDF_Stream* GetAnnotAPNoFallback(CPDF_Dictionary* pAnnotDict,
-                                  CPDF_Annot::AppearanceMode eMode) {
+RetainPtr<CPDF_Stream> GetAnnotAPNoFallback(CPDF_Dictionary* pAnnotDict,
+                                            CPDF_Annot::AppearanceMode eMode) {
   DCHECK(pAnnotDict);
   return GetAnnotAPInternal(pAnnotDict, eMode, false);
 }
 
 CPDF_Form* CPDF_Annot::GetAPForm(const CPDF_Page* pPage, AppearanceMode mode) {
-  CPDF_Stream* pStream = GetAnnotAP(m_pAnnotDict.Get(), mode);
+  RetainPtr<CPDF_Stream> pStream = GetAnnotAP(m_pAnnotDict.Get(), mode);
   if (!pStream)
     return nullptr;
 
@@ -192,8 +194,8 @@
   if (it != m_APMap.end())
     return it->second.get();
 
-  auto pNewForm = std::make_unique<CPDF_Form>(m_pDocument.Get(),
-                                              pPage->GetResources(), pStream);
+  auto pNewForm = std::make_unique<CPDF_Form>(
+      m_pDocument.Get(), pPage->GetResources(), pStream.Get());
   pNewForm->ParseContent();
 
   CPDF_Form* pResult = pNewForm.get();
diff --git a/core/fpdfdoc/cpdf_annot.h b/core/fpdfdoc/cpdf_annot.h
index 2747071..734dcd3 100644
--- a/core/fpdfdoc/cpdf_annot.h
+++ b/core/fpdfdoc/cpdf_annot.h
@@ -13,6 +13,7 @@
 #include <map>
 #include <memory>
 
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fxcrt/bytestring.h"
 #include "core/fxcrt/fx_coordinates.h"
 #include "core/fxcrt/maybe_owned.h"
@@ -26,7 +27,6 @@
 class CPDF_Form;
 class CPDF_Page;
 class CPDF_RenderContext;
-class CPDF_Stream;
 
 class CPDF_Annot {
  public:
@@ -110,7 +110,7 @@
 
   RetainPtr<CPDF_Dictionary> const m_pAnnotDict;
   UnownedPtr<CPDF_Document> const m_pDocument;
-  std::map<const CPDF_Stream*, std::unique_ptr<CPDF_Form>> m_APMap;
+  std::map<RetainPtr<CPDF_Stream>, std::unique_ptr<CPDF_Form>> m_APMap;
   // If non-null, then this is not a popup annotation.
   UnownedPtr<CPDF_Annot> m_pPopupAnnot;
   const Subtype m_nSubtype;
@@ -123,12 +123,12 @@
 // Get the AP in an annotation dict for a given appearance mode.
 // If |eMode| is not Normal and there is not AP for that mode, falls back to
 // the Normal AP.
-CPDF_Stream* GetAnnotAP(CPDF_Dictionary* pAnnotDict,
-                        CPDF_Annot::AppearanceMode eMode);
+RetainPtr<CPDF_Stream> GetAnnotAP(CPDF_Dictionary* pAnnotDict,
+                                  CPDF_Annot::AppearanceMode eMode);
 
 // Get the AP in an annotation dict for a given appearance mode.
 // No fallbacks to Normal like in GetAnnotAP.
-CPDF_Stream* GetAnnotAPNoFallback(CPDF_Dictionary* pAnnotDict,
-                                  CPDF_Annot::AppearanceMode eMode);
+RetainPtr<CPDF_Stream> GetAnnotAPNoFallback(CPDF_Dictionary* pAnnotDict,
+                                            CPDF_Annot::AppearanceMode eMode);
 
 #endif  // CORE_FPDFDOC_CPDF_ANNOT_H_
diff --git a/core/fpdfdoc/cpdf_apsettings.cpp b/core/fpdfdoc/cpdf_apsettings.cpp
index 747e822..2f8cbc5 100644
--- a/core/fpdfdoc/cpdf_apsettings.cpp
+++ b/core/fpdfdoc/cpdf_apsettings.cpp
@@ -10,6 +10,7 @@
 
 #include "core/fpdfapi/parser/cpdf_array.h"
 #include "core/fpdfapi/parser/cpdf_dictionary.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfdoc/cpdf_formcontrol.h"
 
 CPDF_ApSettings::CPDF_ApSettings(CPDF_Dictionary* pDict) : m_pDict(pDict) {}
@@ -97,8 +98,9 @@
   return m_pDict ? m_pDict->GetUnicodeTextFor(csEntry) : WideString();
 }
 
-CPDF_Stream* CPDF_ApSettings::GetIcon(const ByteString& csEntry) const {
-  return m_pDict ? m_pDict->GetStreamFor(csEntry) : nullptr;
+RetainPtr<CPDF_Stream> CPDF_ApSettings::GetIcon(
+    const ByteString& csEntry) const {
+  return m_pDict ? m_pDict->GetMutableStreamFor(csEntry) : nullptr;
 }
 
 CPDF_IconFit CPDF_ApSettings::GetIconFit() const {
diff --git a/core/fpdfdoc/cpdf_apsettings.h b/core/fpdfdoc/cpdf_apsettings.h
index d1cb43e..b5149cb 100644
--- a/core/fpdfdoc/cpdf_apsettings.h
+++ b/core/fpdfdoc/cpdf_apsettings.h
@@ -45,7 +45,7 @@
   CFX_Color GetOriginalColor(const ByteString& csEntry) const;
 
   WideString GetCaption(const ByteString& csEntry) const;
-  CPDF_Stream* GetIcon(const ByteString& csEntry) const;
+  RetainPtr<CPDF_Stream> GetIcon(const ByteString& csEntry) const;
 
  private:
   RetainPtr<CPDF_Dictionary> const m_pDict;
diff --git a/core/fpdfdoc/cpdf_bafontmap.cpp b/core/fpdfdoc/cpdf_bafontmap.cpp
index 149955b..57bddad 100644
--- a/core/fpdfdoc/cpdf_bafontmap.cpp
+++ b/core/fpdfdoc/cpdf_bafontmap.cpp
@@ -297,7 +297,7 @@
   if (ToDictionary(pAPDict->GetObjectFor(m_sAPType)))
     return;
 
-  CPDF_Stream* pStream = pAPDict->GetStreamFor(m_sAPType);
+  RetainPtr<CPDF_Stream> pStream = pAPDict->GetMutableStreamFor(m_sAPType);
   if (!pStream) {
     pStream = m_pDocument->NewIndirect<CPDF_Stream>();
     pAPDict->SetNewFor<CPDF_Reference>(m_sAPType, m_pDocument.Get(),
diff --git a/core/fpdfdoc/cpdf_filespec_unittest.cpp b/core/fpdfdoc/cpdf_filespec_unittest.cpp
index 4b394a0..1dce326 100644
--- a/core/fpdfdoc/cpdf_filespec_unittest.cpp
+++ b/core/fpdfdoc/cpdf_filespec_unittest.cpp
@@ -253,7 +253,7 @@
                                       std::move(pDict));
 
     // Add a params dictionary to the file stream.
-    CPDF_Stream* stream = file_dict->GetStreamFor("UF");
+    RetainPtr<CPDF_Stream> stream = file_dict->GetMutableStreamFor("UF");
     CPDF_Dictionary* stream_dict = stream->GetDict();
     stream_dict->SetNewFor<CPDF_Dictionary>("Params");
     EXPECT_TRUE(file_spec.GetParamsDict());
diff --git a/core/fpdfdoc/cpdf_formcontrol.cpp b/core/fpdfdoc/cpdf_formcontrol.cpp
index a2ce749..cdb8dd3 100644
--- a/core/fpdfdoc/cpdf_formcontrol.cpp
+++ b/core/fpdfdoc/cpdf_formcontrol.cpp
@@ -167,7 +167,7 @@
   return GetMK().GetCaption(csEntry);
 }
 
-CPDF_Stream* CPDF_FormControl::GetIcon(const ByteString& csEntry) {
+RetainPtr<CPDF_Stream> CPDF_FormControl::GetIcon(const ByteString& csEntry) {
   return GetMK().GetIcon(csEntry);
 }
 
diff --git a/core/fpdfdoc/cpdf_formcontrol.h b/core/fpdfdoc/cpdf_formcontrol.h
index d47b720..2a49349 100644
--- a/core/fpdfdoc/cpdf_formcontrol.h
+++ b/core/fpdfdoc/cpdf_formcontrol.h
@@ -74,9 +74,15 @@
     return GetCaption(pdfium::appearance::kAC);
   }
 
-  CPDF_Stream* GetNormalIcon() { return GetIcon(pdfium::appearance::kI); }
-  CPDF_Stream* GetRolloverIcon() { return GetIcon(pdfium::appearance::kRI); }
-  CPDF_Stream* GetDownIcon() { return GetIcon(pdfium::appearance::kIX); }
+  RetainPtr<CPDF_Stream> GetNormalIcon() {
+    return GetIcon(pdfium::appearance::kI);
+  }
+  RetainPtr<CPDF_Stream> GetRolloverIcon() {
+    return GetIcon(pdfium::appearance::kRI);
+  }
+  RetainPtr<CPDF_Stream> GetDownIcon() {
+    return GetIcon(pdfium::appearance::kIX);
+  }
   CPDF_IconFit GetIconFit() const;
 
   int GetTextPosition() const;
@@ -93,7 +99,7 @@
   CFX_Color GetOriginalColor(const ByteString& csEntry);
 
   WideString GetCaption(const ByteString& csEntry) const;
-  CPDF_Stream* GetIcon(const ByteString& csEntry);
+  RetainPtr<CPDF_Stream> GetIcon(const ByteString& csEntry);
   CPDF_ApSettings GetMK() const;
 
   UnownedPtr<CPDF_FormField> const m_pField;
diff --git a/core/fpdfdoc/cpdf_formfield.cpp b/core/fpdfdoc/cpdf_formfield.cpp
index d76cf89..3b4d38e 100644
--- a/core/fpdfdoc/cpdf_formfield.cpp
+++ b/core/fpdfdoc/cpdf_formfield.cpp
@@ -19,6 +19,7 @@
 #include "core/fpdfapi/parser/cpdf_dictionary.h"
 #include "core/fpdfapi/parser/cpdf_name.h"
 #include "core/fpdfapi/parser/cpdf_number.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfapi/parser/cpdf_string.h"
 #include "core/fpdfapi/parser/fpdf_parser_decode.h"
 #include "core/fpdfapi/parser/fpdf_parser_utility.h"
diff --git a/core/fpdfdoc/cpdf_generateap.cpp b/core/fpdfdoc/cpdf_generateap.cpp
index f75fc54..cab747b 100644
--- a/core/fpdfdoc/cpdf_generateap.cpp
+++ b/core/fpdfdoc/cpdf_generateap.cpp
@@ -1068,7 +1068,7 @@
 
   CPDF_Dictionary* pAPDict =
       GetOrCreateDict(pAnnotDict, pdfium::annotation::kAP);
-  CPDF_Stream* pNormalStream = pAPDict->GetStreamFor("N");
+  RetainPtr<CPDF_Stream> pNormalStream = pAPDict->GetMutableStreamFor("N");
   if (!pNormalStream) {
     pNormalStream = pDoc->NewIndirect<CPDF_Stream>();
     pAPDict->SetNewFor<CPDF_Reference>("N", pDoc, pNormalStream->GetObjNum());
diff --git a/core/fpdfdoc/cpdf_interactiveform.cpp b/core/fpdfdoc/cpdf_interactiveform.cpp
index e43cf81..b998a6f 100644
--- a/core/fpdfdoc/cpdf_interactiveform.cpp
+++ b/core/fpdfdoc/cpdf_interactiveform.cpp
@@ -23,6 +23,7 @@
 #include "core/fpdfapi/parser/cpdf_document.h"
 #include "core/fpdfapi/parser/cpdf_name.h"
 #include "core/fpdfapi/parser/cpdf_reference.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfapi/parser/cpdf_string.h"
 #include "core/fpdfapi/parser/fpdf_parser_utility.h"
 #include "core/fpdfdoc/cpdf_filespec.h"
diff --git a/fpdfsdk/cpdfsdk_appstream.cpp b/fpdfsdk/cpdfsdk_appstream.cpp
index 805394f..9490229 100644
--- a/fpdfsdk/cpdfsdk_appstream.cpp
+++ b/fpdfsdk/cpdfsdk_appstream.cpp
@@ -1227,9 +1227,9 @@
   if (pControl->HasMKEntry(pdfium::appearance::kAC))
     csDownCaption = pControl->GetDownCaption();
 
-  CPDF_Stream* pNormalIcon = nullptr;
-  CPDF_Stream* pRolloverIcon = nullptr;
-  CPDF_Stream* pDownIcon = nullptr;
+  RetainPtr<CPDF_Stream> pNormalIcon;
+  RetainPtr<CPDF_Stream> pRolloverIcon;
+  RetainPtr<CPDF_Stream> pDownIcon;
   if (pControl->HasMKEntry(pdfium::appearance::kI))
     pNormalIcon = pControl->GetNormalIcon();
 
@@ -1239,9 +1239,9 @@
   if (pControl->HasMKEntry(pdfium::appearance::kIX))
     pDownIcon = pControl->GetDownIcon();
 
-  SetDefaultIconName(pNormalIcon, "ImgA");
-  SetDefaultIconName(pRolloverIcon, "ImgB");
-  SetDefaultIconName(pDownIcon, "ImgC");
+  SetDefaultIconName(pNormalIcon.Get(), "ImgA");
+  SetDefaultIconName(pRolloverIcon.Get(), "ImgB");
+  SetDefaultIconName(pDownIcon.Get(), "ImgC");
 
   CPDF_IconFit iconFit = pControl->GetIconFit();
   {
@@ -1252,12 +1252,12 @@
         GetBorderAppStreamInternal(rcWindow, fBorderWidth, crBorder, crLeftTop,
                                    crRightBottom, nBorderStyle, dsBorder) +
         GetPushButtonAppStream(iconFit.GetFittingBounds() ? rcWindow : rcClient,
-                               &font_map, pNormalIcon, iconFit, csNormalCaption,
-                               crText, fFontSize, nLayout);
+                               &font_map, pNormalIcon.Get(), iconFit,
+                               csNormalCaption, crText, fFontSize, nLayout);
 
     Write("N", csAP, ByteString());
     if (pNormalIcon)
-      AddImage("N", pNormalIcon);
+      AddImage("N", pNormalIcon.Get());
 
     CPDF_FormControl::HighlightingMode eHLM = pControl->GetHighlightingMode();
     if (eHLM != CPDF_FormControl::kPush && eHLM != CPDF_FormControl::kToggle) {
@@ -1279,12 +1279,12 @@
         GetBorderAppStreamInternal(rcWindow, fBorderWidth, crBorder, crLeftTop,
                                    crRightBottom, nBorderStyle, dsBorder) +
         GetPushButtonAppStream(iconFit.GetFittingBounds() ? rcWindow : rcClient,
-                               &font_map, pRolloverIcon, iconFit,
+                               &font_map, pRolloverIcon.Get(), iconFit,
                                csRolloverCaption, crText, fFontSize, nLayout);
 
     Write("R", csAP, ByteString());
     if (pRolloverIcon)
-      AddImage("R", pRolloverIcon);
+      AddImage("R", pRolloverIcon.Get());
 
     if (csDownCaption.IsEmpty() && !pDownIcon) {
       csDownCaption = csNormalCaption;
@@ -1315,12 +1315,12 @@
         GetBorderAppStreamInternal(rcWindow, fBorderWidth, crBorder, crLeftTop,
                                    crRightBottom, nBorderStyle, dsBorder) +
         GetPushButtonAppStream(iconFit.GetFittingBounds() ? rcWindow : rcClient,
-                               &font_map, pDownIcon, iconFit, csDownCaption,
-                               crText, fFontSize, nLayout);
+                               &font_map, pDownIcon.Get(), iconFit,
+                               csDownCaption, crText, fFontSize, nLayout);
 
     Write("D", csAP, ByteString());
     if (pDownIcon)
-      AddImage("D", pDownIcon);
+      AddImage("D", pDownIcon.Get());
   }
 }
 
@@ -1825,7 +1825,7 @@
 
 void CPDFSDK_AppStream::AddImage(const ByteString& sAPType,
                                  CPDF_Stream* pImage) {
-  CPDF_Stream* pStream = dict_->GetStreamFor(sAPType);
+  RetainPtr<CPDF_Stream> pStream = dict_->GetMutableStreamFor(sAPType);
   CPDF_Dictionary* pStreamDict = pStream->GetDict();
   ByteString sImageAlias = "IMG";
 
@@ -1858,9 +1858,9 @@
 
   // If `pStream` is created by CreateModifiedAPStream(), then it is safe to
   // edit, as it is not shared.
-  CPDF_Stream* pStream = pParentDict->GetStreamFor(key);
+  RetainPtr<CPDF_Stream> pStream = pParentDict->GetMutableStreamFor(key);
   CPDF_Document* doc = widget_->GetPageView()->GetPDFDocument();
-  if (!doc->IsModifiedAPStream(pStream)) {
+  if (!doc->IsModifiedAPStream(pStream.Get())) {
     if (pStream)
       pOrigStreamDict = pStream->GetDict();
     pStream = doc->CreateModifiedAPStream();
diff --git a/fpdfsdk/fpdf_annot.cpp b/fpdfsdk/fpdf_annot.cpp
index ee909ff..a775c53 100644
--- a/fpdfsdk/fpdf_annot.cpp
+++ b/fpdfsdk/fpdf_annot.cpp
@@ -214,7 +214,7 @@
   DCHECK(annot_dict);
   // Update BBox entry in appearance stream based on the bounding rectangle
   // of the annotation's quadpoints.
-  CPDF_Stream* pStream =
+  RetainPtr<CPDF_Stream> pStream =
       GetAnnotAP(annot_dict, CPDF_Annot::AppearanceMode::kNormal);
   if (pStream) {
     CFX_FloatRect boundingRect =
@@ -470,7 +470,7 @@
   // Check that the annotation already has an appearance stream, since an
   // existing object is to be updated.
   RetainPtr<CPDF_Dictionary> pAnnotDict = pAnnot->GetMutableAnnotDict();
-  CPDF_Stream* pStream =
+  RetainPtr<CPDF_Stream> pStream =
       GetAnnotAP(pAnnotDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
   if (!pStream)
     return false;
@@ -486,7 +486,7 @@
     return false;
 
   // Update the content stream data in the annotation's AP stream.
-  UpdateContentStream(pForm, pStream);
+  UpdateContentStream(pForm, pStream.Get());
   return true;
 }
 
@@ -540,7 +540,7 @@
 
   // If the annotation does not have an AP stream yet, generate and set it.
   RetainPtr<CPDF_Dictionary> pAnnotDict = pAnnot->GetMutableAnnotDict();
-  CPDF_Stream* pStream =
+  RetainPtr<CPDF_Stream> pStream =
       GetAnnotAP(pAnnotDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
   if (!pStream) {
     CPDF_GenerateAP::GenerateEmptyAP(pAnnot->GetPage()->GetDocument(),
@@ -552,7 +552,7 @@
 
   // Get the annotation's corresponding form object for parsing its AP stream.
   if (!pAnnot->HasForm())
-    pAnnot->SetForm(pStream);
+    pAnnot->SetForm(pStream.Get());
 
   // Check that the object did not come from the same annotation. If this check
   // succeeds, then it is assumed that the object came from
@@ -572,7 +572,7 @@
   pForm->AppendPageObject(pdfium::WrapUnique(pObj));
 
   // Set the content stream data in the annotation's AP stream.
-  UpdateContentStream(pForm, pStream);
+  UpdateContentStream(pForm, pStream.Get());
   return true;
 }
 
@@ -583,12 +583,12 @@
 
   if (!pAnnot->HasForm()) {
     RetainPtr<CPDF_Dictionary> pDict = pAnnot->GetMutableAnnotDict();
-    CPDF_Stream* pStream =
+    RetainPtr<CPDF_Stream> pStream =
         GetAnnotAP(pDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
     if (!pStream)
       return 0;
 
-    pAnnot->SetForm(pStream);
+    pAnnot->SetForm(pStream.Get());
   }
   return pdfium::base::checked_cast<int>(
       pAnnot->GetForm()->GetPageObjectCount());
@@ -602,12 +602,12 @@
 
   if (!pAnnot->HasForm()) {
     RetainPtr<CPDF_Dictionary> pAnnotDict = pAnnot->GetMutableAnnotDict();
-    CPDF_Stream* pStream =
+    RetainPtr<CPDF_Stream> pStream =
         GetAnnotAP(pAnnotDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
     if (!pStream)
       return nullptr;
 
-    pAnnot->SetForm(pStream);
+    pAnnot->SetForm(pStream.Get());
   }
 
   return FPDFPageObjectFromCPDFPageObject(
@@ -627,7 +627,7 @@
   // Check that the annotation already has an appearance stream, since an
   // existing object is to be deleted.
   RetainPtr<CPDF_Dictionary> pAnnotDict = pAnnot->GetMutableAnnotDict();
-  CPDF_Stream* pStream =
+  RetainPtr<CPDF_Stream> pStream =
       GetAnnotAP(pAnnotDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
   if (!pStream)
     return false;
@@ -635,7 +635,7 @@
   if (!pAnnot->GetForm()->ErasePageObjectAtIndex(index))
     return false;
 
-  UpdateContentStream(pAnnot->GetForm(), pStream);
+  UpdateContentStream(pAnnot->GetForm(), pStream.Get());
   return true;
 }
 
@@ -833,7 +833,7 @@
   if (FPDFAnnot_HasAttachmentPoints(annot))
     return true;
 
-  CPDF_Stream* pStream =
+  RetainPtr<CPDF_Stream> pStream =
       GetAnnotAP(pAnnotDict.Get(), CPDF_Annot::AppearanceMode::kNormal);
   if (pStream && newRect.Contains(pStream->GetDict()->GetRectFor("BBox")))
     pStream->GetDict()->SetRectFor("BBox", newRect);
@@ -1134,7 +1134,7 @@
   CPDF_Annot::AppearanceMode mode =
       static_cast<CPDF_Annot::AppearanceMode>(appearanceMode);
 
-  CPDF_Stream* pStream = GetAnnotAPNoFallback(pAnnotDict.Get(), mode);
+  RetainPtr<CPDF_Stream> pStream = GetAnnotAPNoFallback(pAnnotDict.Get(), mode);
   return Utf16EncodeMaybeCopyAndReturnLength(
       pStream ? pStream->GetUnicodeText() : WideString(), buffer, buflen);
 }
diff --git a/fpdfsdk/fpdf_flatten.cpp b/fpdfsdk/fpdf_flatten.cpp
index 9eb3179..f04ba47 100644
--- a/fpdfsdk/fpdf_flatten.cpp
+++ b/fpdfsdk/fpdf_flatten.cpp
@@ -192,8 +192,8 @@
                      CPDF_Document* pDocument) {
   RetainPtr<CPDF_Array> pContentsArray =
       pPage->GetMutableArrayFor(pdfium::page_object::kContents);
-  CPDF_Stream* pContentsStream =
-      pPage->GetStreamFor(pdfium::page_object::kContents);
+  RetainPtr<CPDF_Stream> pContentsStream =
+      pPage->GetMutableStreamFor(pdfium::page_object::kContents);
   if (!pContentsStream && !pContentsArray) {
     if (!key.IsEmpty()) {
       pPage->SetFor(
@@ -213,7 +213,7 @@
   } else {
     ByteString sStream = "q\n";
     {
-      auto pAcc = pdfium::MakeRetain<CPDF_StreamAcc>(pContentsStream);
+      auto pAcc = pdfium::MakeRetain<CPDF_StreamAcc>(pContentsStream.Get());
       pAcc->LoadAllDataFiltered();
       sStream += ByteString(pAcc->GetSpan());
       sStream += "\nQ";
@@ -342,14 +342,14 @@
     if (!pAnnotAP)
       continue;
 
-    CPDF_Stream* pAPStream = pAnnotAP->GetStreamFor("N");
+    RetainPtr<CPDF_Stream> pAPStream = pAnnotAP->GetMutableStreamFor("N");
     if (!pAPStream) {
       RetainPtr<CPDF_Dictionary> pAPDict = pAnnotAP->GetMutableDictFor("N");
       if (!pAPDict)
         continue;
 
       if (!sAnnotState.IsEmpty()) {
-        pAPStream = pAPDict->GetStreamFor(sAnnotState);
+        pAPStream = pAPDict->GetMutableStreamFor(sAnnotState);
       } else {
         if (pAPDict->size() > 0) {
           CPDF_DictionaryLocker locker(pAPDict.Get());
@@ -367,7 +367,7 @@
     if (!pAPStream)
       continue;
 
-    CPDF_Dictionary* pAPDict = pAPStream->GetDict();
+    const CPDF_Dictionary* pAPDict = pAPStream->GetDict();
     CFX_FloatRect rcStream;
     if (pAPDict->KeyExist("Rect"))
       rcStream = pAPDict->GetRectFor("Rect");
@@ -378,7 +378,7 @@
     if (rcStream.IsEmpty())
       continue;
 
-    CPDF_Object* pObj = pAPStream;
+    RetainPtr<CPDF_Object> pObj = pAPStream;
     if (pObj->IsInline()) {
       RetainPtr<CPDF_Object> pNew = pObj->Clone();
       pObj = pNew.Get();
diff --git a/fpdfsdk/fpdf_formfill.cpp b/fpdfsdk/fpdf_formfill.cpp
index d37bf63..b8a496a 100644
--- a/fpdfsdk/fpdf_formfill.cpp
+++ b/fpdfsdk/fpdf_formfill.cpp
@@ -15,6 +15,7 @@
 #include "core/fpdfapi/page/cpdf_page.h"
 #include "core/fpdfapi/parser/cpdf_dictionary.h"
 #include "core/fpdfapi/parser/cpdf_document.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfapi/render/cpdf_renderoptions.h"
 #include "core/fpdfdoc/cpdf_formcontrol.h"
 #include "core/fpdfdoc/cpdf_formfield.h"
diff --git a/fxjs/cjs_field.cpp b/fxjs/cjs_field.cpp
index ff8f49a..84ddc8e 100644
--- a/fxjs/cjs_field.cpp
+++ b/fxjs/cjs_field.cpp
@@ -13,6 +13,7 @@
 #include "constants/access_permissions.h"
 #include "constants/annotation_flags.h"
 #include "constants/form_flags.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfdoc/cpdf_formcontrol.h"
 #include "core/fpdfdoc/cpdf_formfield.h"
 #include "core/fpdfdoc/cpdf_interactiveform.h"
diff --git a/fxjs/cjs_publicmethods.cpp b/fxjs/cjs_publicmethods.cpp
index 4f0dc66..af27d0f 100644
--- a/fxjs/cjs_publicmethods.cpp
+++ b/fxjs/cjs_publicmethods.cpp
@@ -18,6 +18,7 @@
 #include <vector>
 
 #include "build/build_config.h"
+#include "core/fpdfapi/parser/cpdf_stream.h"
 #include "core/fpdfdoc/cpdf_formcontrol.h"
 #include "core/fpdfdoc/cpdf_interactiveform.h"
 #include "core/fxcrt/fx_extension.h"