Squashed 'third_party/autocxx/' content from commit 629e8fa53

git-subtree-dir: third_party/autocxx
git-subtree-split: 629e8fa531a633164c0b52e2a3cab536d4cd0849
Signed-off-by: Brian Silverman <bsilver16384@gmail.com>
Change-Id: I62a03b0049f49adf029e0204639cdb5468dde1a1
diff --git a/examples/chromium-fake-render-frame-host/src/fake-chromium-header.h b/examples/chromium-fake-render-frame-host/src/fake-chromium-header.h
new file mode 100644
index 0000000..8f1c532
--- /dev/null
+++ b/examples/chromium-fake-render-frame-host/src/fake-chromium-header.h
@@ -0,0 +1,78 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#pragma once
+#include <memory>
+#include <string>
+#include <vector>
+
+// This is supposed to be a _fairly_ faithful representation of a few
+// Chromium codebase APIs. Just enough that we can start to experiment
+// with ownership patterns.
+
+namespace content {
+
+class RenderFrameHost {
+public:
+  static RenderFrameHost *FromId(int process_id, int frame_id);
+  virtual int GetRoutingID() = 0;
+
+  /// Returns the assigned name of the frame, the name of the iframe tag
+  /// declaring it. For example, <iframe name="framename">[...]</iframe>. It is
+  /// quite possible for a frame to have no name, in which case GetFrameName
+  /// will return an empty string.
+  virtual std::string GetFrameName() = 0;
+  virtual ~RenderFrameHost() {}
+};
+
+class CreateParams {
+public:
+  CreateParams(const std::string &);
+  std::string main_frame_name_;
+};
+
+class WebContentsObserver;
+
+class WebContents {
+public:
+  static std::unique_ptr<WebContents> Create(const CreateParams &params);
+
+  static WebContents *FromFrameTreeNodeId(int frame_tree_node_id);
+
+  // TODO - should not be in WebContents, just WebContentsImpl
+  virtual void AddObserver(WebContentsObserver *) {}
+  virtual void RemoveObserver(WebContentsObserver *) {}
+
+  virtual ~WebContents(){};
+
+  virtual const std::string &GetTitle() = 0;
+};
+
+class WebContentsObserver {
+public:
+  virtual void RenderFrameCreated(RenderFrameHost *) {}
+  virtual void RenderFrameDeleted(RenderFrameHost *) {}
+  virtual ~WebContentsObserver() {}
+};
+
+class WebContentsImpl : public WebContents {
+public:
+  void AddObserver(WebContentsObserver *);
+  void RemoveObserver(WebContentsObserver *);
+  const std::string &GetTitle();
+  WebContentsImpl(const CreateParams &);
+  void DeleteRFH();
+
+private:
+  std::string title_;
+  std::vector<WebContentsObserver *> observers_;
+  std::vector<std::unique_ptr<RenderFrameHost>> rfhs_;
+};
+} // namespace content
+
+void SimulateRendererShutdown(int frame_id);
\ No newline at end of file
diff --git a/examples/chromium-fake-render-frame-host/src/fake-chromium-src.cc b/examples/chromium-fake-render-frame-host/src/fake-chromium-src.cc
new file mode 100644
index 0000000..2f9a9d4
--- /dev/null
+++ b/examples/chromium-fake-render-frame-host/src/fake-chromium-src.cc
@@ -0,0 +1,81 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#include "fake-chromium-header.h"
+#include <map>
+#include <algorithm>
+
+using namespace content;
+
+// This is all appalling. None of this is real Chromium code.
+// It's just designed to be the bare minimum required
+// to knock together a quick Rust-side demo. In some future realities, all
+// this is replaced with real Chromium code.
+
+int latest_rfh_id = 0;
+std::map<int, RenderFrameHost *> render_frame_hosts;
+WebContentsImpl *the_only_web_contents; // for this daft demo
+
+CreateParams::CreateParams(const std::string &main_frame_name)
+    : main_frame_name_(main_frame_name) {}
+
+RenderFrameHost *RenderFrameHost::FromId(int, int frame_id) {
+  return render_frame_hosts.at(frame_id);
+}
+
+class RenderFrameHostImpl : public RenderFrameHost {
+public:
+  RenderFrameHostImpl(const std::string name, int routing_id)
+      : routing_id_(routing_id), name_(name) {}
+  virtual int GetRoutingID() { return routing_id_; }
+  virtual std::string GetFrameName() { return name_; }
+
+private:
+  int routing_id_;
+  std::string name_;
+};
+
+std::unique_ptr<WebContents> WebContents::Create(const CreateParams &params) {
+  auto wc = std::make_unique<WebContentsImpl>(params);
+  the_only_web_contents = wc.get();
+  return wc;
+}
+
+WebContentsImpl::WebContentsImpl(const CreateParams &params)
+    : title_(params.main_frame_name_) {
+  int id = latest_rfh_id++;
+  std::unique_ptr<RenderFrameHost> new_rfh(
+      new RenderFrameHostImpl(params.main_frame_name_, id));
+  render_frame_hosts.insert(
+      std::pair<int, RenderFrameHost *>(id, new_rfh.get()));
+  for (auto obs : observers_) {
+    obs->RenderFrameCreated(new_rfh.get());
+  }
+  rfhs_.push_back(std::move(new_rfh));
+}
+
+void WebContentsImpl::AddObserver(WebContentsObserver *observer) {
+  observers_.push_back(observer);
+}
+void WebContentsImpl::RemoveObserver(WebContentsObserver *observer) {
+  std::remove(std::begin(observers_), std::end(observers_), observer);
+}
+
+void WebContentsImpl::DeleteRFH() {
+  for (auto obs : observers_) {
+    obs->RenderFrameDeleted(rfhs_[0].get());
+  }
+  rfhs_.clear();
+}
+
+const std::string &WebContentsImpl::GetTitle() { return title_; }
+
+void SimulateRendererShutdown(int frame_id) {
+  render_frame_hosts.erase(frame_id);
+  the_only_web_contents->DeleteRFH();
+}
diff --git a/examples/chromium-fake-render-frame-host/src/main.rs b/examples/chromium-fake-render-frame-host/src/main.rs
new file mode 100644
index 0000000..d2504dc
--- /dev/null
+++ b/examples/chromium-fake-render-frame-host/src/main.rs
@@ -0,0 +1,73 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use autocxx::prelude::*;
+mod render_frame_host;
+use render_frame_host::RenderFrameHostForWebContents;
+use render_frame_host::RenderFrameHostHandle;
+
+include_cpp! {
+    #include "fake-chromium-header.h"
+    safety!(unsafe) // unsafety policy; see docs
+    generate!("content::WebContents")
+    generate!("content::RenderFrameHost")
+    generate!("content::CreateParams")
+    generate!("SimulateRendererShutdown")
+    subclass!("content::WebContentsObserver",RenderFrameHostForWebContents)
+}
+
+use ffi::ToCppString;
+
+fn main() {
+    // Create some fake toy WebContents.
+    let create_params = ffi::content::CreateParams::new(&"silly-frame".into_cpp()).within_unique_ptr();
+    let mut frame = ffi::content::WebContents::Create(&create_params);
+
+    // This object is a memory-safe handle to a RenderFrameHost.
+    // On creation, we pass it the WebContents, such that it can register
+    // to be informed of the destruction of the RenderFrameHost.
+    // It also happens to store a reference to that WebContents,
+    // so the compiler will prove that this RenderFrameHostHandle
+    // can't outlive the WebContents. That's nice. But currently
+    // it stores an exclusive (a.k.a. mutable) reference, and we may
+    // well want to relax that in future.
+    // (This relates to https://github.com/google/autocxx/issues/622)
+    let mut rfh_handle = RenderFrameHostHandle::from_id(c_int(3), c_int(0), frame.pin_mut());
+
+    // We can directly call methods on the RFH.
+    // (If this were a 'const' method, the `.pin_mut()` wouldn't be necessary).
+    let frame_name = rfh_handle.pin_mut().GetFrameName();
+    println!("Frame name is {}", frame_name.to_str().unwrap());
+
+    {
+        // We can also borrow the RFH and use Rust's borrow checker to ensure
+        // no other code can do so. This also gives us a chance to explicitly
+        // handle the case where the RFH was already destroyed, in case
+        // we want to do something smarter than panicking.
+        let mut rfh_borrowed = rfh_handle
+            .try_borrow_mut()
+            .expect("Oh! The RFH was already destroyed!");
+        // Nobody else can borrow it during this time...
+        //   let mut rfh_borrowed_again = rfh_handle.try_borrow_mut().unwrap();
+        // Gives compile-time error "second mutable borrow occurs here..."
+        let frame_name = rfh_borrowed.pin_mut().GetFrameName();
+        println!("Frame name is {}", frame_name.to_str().unwrap());
+        let frame_name = rfh_borrowed.pin_mut().GetFrameName();
+        println!("Frame name is {}", frame_name.to_str().unwrap());
+
+        // Supposing we end up calling some code deep in the Chrome C++
+        // stack which destroys the RFH whilst it's still borrowed.
+        // That will result in a runtime panic...
+        //  ffi::SimulateRendererShutdown(c_int(0)); // would panic
+    }
+
+    // But let's assume we've now returned to the event loop.
+    // None of the previous borrows still exist. It's perfectly OK to now
+    // delete the RFH.
+    ffi::SimulateRendererShutdown(c_int(0));
+}
diff --git a/examples/chromium-fake-render-frame-host/src/render_frame_host.rs b/examples/chromium-fake-render-frame-host/src/render_frame_host.rs
new file mode 100644
index 0000000..9c2bf51
--- /dev/null
+++ b/examples/chromium-fake-render-frame-host/src/render_frame_host.rs
@@ -0,0 +1,242 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use autocxx::subclass::prelude::*;
+use autocxx::{c_int, PinMut};
+use std::cell::{Ref, RefCell, RefMut};
+use std::ops::Deref;
+use std::pin::Pin;
+use std::rc::Rc;
+
+use crate::ffi;
+
+/// A memory-safe handle to a C++ RenderFrameHost.
+///
+/// This is a toy, hypothetical, example.
+///
+/// Creation: in this sample, the only option is to use [`RenderFrameHostHandle::from_id`]
+/// which corresponds to the equivalent method in C++ `RenderFrameHost`. Unlike
+/// the C++ version, you must pass a WebContents so that Rust wrappers can listen for
+/// destruction events.
+///
+/// The returned handle is memory safe and can be used to access the methods
+/// of [`ffi::content::RenderFrameHost`]. To use such a method, you have three options:
+/// * If you believe there is no chance that the `RenderFrameHost` has been
+///   destroyed, and if the method is const, you can just go ahead and call methods
+///   on this object. As it implements [`std::ops::Deref`], that will just work -
+///   but your code will panic if the `RenderFrameHost` was already destroyed.
+/// * If the method is non-const, you'll have to call `.pin_mut().method()` instead
+//    but otherwise this is functionally identical.
+/// * If you believe that there is a chance that the `RenderFrameHost` was already
+///   destroyed, use [`RenderFrameHostHandle::try_borrow`] or
+///   [`RenderFrameHostHandle::try_borrow_mut`]. This will return
+///   a guard object which guarantees the existence of the `RenderFrameHost`
+///   during its lifetime.
+///
+/// # Performance characteristics
+///
+/// The existence of this object registers an observer with the `WebContents`
+/// and deregisters it on destruction. That is, of course, an overhead, but
+/// that's necessary to keep track of liveness. (A more efficient
+/// implementation would use a single observer for multiple such handles - but
+/// this is a toy implementation).
+///
+/// In addition, each time you extract the value from this
+/// `RenderFrameHostHandle`, a liveness check is performed. This involves
+/// not just a null check but also some reference count manipulation.
+/// If you're going to access the `RenderFrameHost` multiple times, it's
+/// advised that you call [`RenderFrameHostHandle::try_borrow`] or
+/// [`RenderFrameHostHandle::try_borrow_mut`] and then use
+/// the result multiple times. The liveness check for the `RenderFrameHost`
+/// will be performed only once at runtime.
+///
+/// # Destruction of RenderFrameHosts while borrowed
+///
+/// If you have called [`RenderFrameHostHandle::try_borrow`] (or its mutable
+/// equivalent) and still have an outstanding borrow, any code path - via C++
+/// - which results it the destruction of the `RenderFrameHost` will result in
+/// a runtime panic.
+pub struct RenderFrameHostHandle<'wc> {
+    obs: Rc<RefCell<RenderFrameHostForWebContents>>,
+    web_contents: Pin<&'wc mut ffi::content::WebContents>,
+}
+
+impl<'wc> RenderFrameHostHandle<'wc> {
+    /// Create a memory-safe handle to a RenderFrameHost using its
+    /// process ID and frame ID.
+    pub fn from_id(
+        render_process_id: c_int,
+        render_frame_id: c_int,
+        mut web_contents: Pin<&'wc mut ffi::content::WebContents>,
+    ) -> Self {
+        // Instantiate our WebContentsObserver subclass.
+        let obs = RenderFrameHostForWebContents::new_rust_owned(RenderFrameHostForWebContents {
+            rfh: ffi::content::RenderFrameHost::FromId(render_process_id, render_frame_id),
+            cpp_peer: Default::default(),
+        });
+
+        // And now register it.
+        // This nasty line will go away when autocxx is a bit more sophisticated.
+        let superclass_ptr = cast_to_superclass(obs.as_ref().borrow_mut().peer_mut());
+
+        // But this will remain unsafe. cxx policy is that any raw pointer
+        // passed into a C++ function requires an unsafe {} block and that
+        // is sensible. We may of course provide an ergonomic Rust wrapper
+        // around WebContents which provides safe Rust equivalents
+        // (using references or similar rather than pointers) in which case
+        // this unsafe block would go away.
+        unsafe { web_contents.as_mut().AddObserver(superclass_ptr) };
+
+        Self { obs, web_contents }
+    }
+
+    /// Tries to return a mutable reference to the RenderFrameHost.
+    /// Because this requires `self` to be `&mut`, and that lifetime is
+    /// applied to the returned `RenderFrameHost`, the compiler will prevent
+    /// multiple such references existing in Rust at the same time.
+    /// This will return `None` if the RenderFrameHost were already destroyed.
+    pub fn try_borrow_mut<'a>(
+        &'a mut self,
+    ) -> Option<impl PinMut<ffi::content::RenderFrameHost> + 'a> {
+        let ref_mut = self.obs.as_ref().borrow_mut();
+        if ref_mut.rfh.is_null() {
+            None
+        } else {
+            Some(RenderFrameHostRefMut(ref_mut))
+        }
+    }
+
+    /// Tries to return a reference to the RenderFrameHost.
+    /// The compiler will prevent calls to this if anyone has an outstanding
+    /// mutable reference from [`RenderFrameHostHandle::try_borrow_mut`].
+    /// This will return `None` if the RenderFrameHost were already destroyed.
+    #[allow(dead_code)]
+    pub fn try_borrow<'a>(&'a self) -> Option<impl AsRef<ffi::content::RenderFrameHost> + 'a> {
+        let ref_non_mut = self.obs.as_ref().borrow();
+        if ref_non_mut.rfh.is_null() {
+            None
+        } else {
+            Some(RenderFrameHostRef(ref_non_mut))
+        }
+    }
+}
+
+impl<'wc> Drop for RenderFrameHostHandle<'wc> {
+    fn drop(&mut self) {
+        // Unregister our observer.
+        let superclass_ptr = cast_to_superclass(self.obs.as_ref().borrow_mut().peer_mut());
+        unsafe { self.web_contents.as_mut().RemoveObserver(superclass_ptr) };
+    }
+}
+
+impl<'wc> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
+    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
+        let ref_non_mut = self.obs.as_ref().borrow();
+        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
+        // and we are observing its lifetime so it will be reset to null
+        // if destroyed.
+        unsafe { ref_non_mut.rfh.as_ref() }.expect("This RenderFrameHost was already destroyed")
+    }
+}
+
+impl<'wc> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
+    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
+        let ref_mut = self.obs.as_ref().borrow_mut();
+        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
+        // and we are observing its lifetime so it will be reset to null
+        // if destroyed.
+        unsafe { ref_mut.rfh.as_mut().map(|p| Pin::new_unchecked(p)) }
+            .expect("This RenderFrameHost was already destroyed")
+    }
+}
+
+impl<'wc> Deref for RenderFrameHostHandle<'wc> {
+    type Target = ffi::content::RenderFrameHost;
+    fn deref(&self) -> &Self::Target {
+        self.as_ref()
+    }
+}
+
+#[doc(hidden)]
+struct RenderFrameHostRefMut<'a>(RefMut<'a, RenderFrameHostForWebContents>);
+
+#[doc(hidden)]
+struct RenderFrameHostRef<'a>(Ref<'a, RenderFrameHostForWebContents>);
+
+impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRef<'a> {
+    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
+        // Safety:
+        // Creation precondition is that self.0.rfh is not null
+        // and it can't be destroyed whilst this borrow exists.
+        unsafe { self.0.rfh.as_ref().unwrap() }
+    }
+}
+
+impl<'a> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
+    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
+        // Safety:
+        // Creation precondition is that self.0.rfh is not null
+        // and it can't be destroyed whilst this borrow exists.
+        unsafe { Pin::new_unchecked(self.0.rfh.as_mut().unwrap()) }
+    }
+}
+
+impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
+    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
+        // Safety:
+        // Creation precondition is that self.0.rfh is not null
+        // and it can't be destroyed whilst this borrow exists.
+        unsafe { self.0.rfh.as_ref().unwrap() }
+    }
+}
+
+impl<'a> Deref for RenderFrameHostRef<'a> {
+    type Target = ffi::content::RenderFrameHost;
+    fn deref(&self) -> &Self::Target {
+        self.as_ref()
+    }
+}
+
+impl<'a> Deref for RenderFrameHostRefMut<'a> {
+    type Target = ffi::content::RenderFrameHost;
+    fn deref(&self) -> &Self::Target {
+        self.as_ref()
+    }
+}
+
+#[is_subclass(superclass("content::WebContentsObserver"))]
+#[doc(hidden)]
+pub struct RenderFrameHostForWebContents {
+    rfh: *mut ffi::content::RenderFrameHost,
+}
+
+impl ffi::content::WebContentsObserver_methods for RenderFrameHostForWebContents {
+    unsafe fn RenderFrameDeleted(&mut self, destroyed_rfh: *mut ffi::content::RenderFrameHost) {
+        if self.rfh == destroyed_rfh {
+            self.rfh = std::ptr::null_mut()
+        }
+    }
+}
+
+fn cast_to_superclass(
+    obs: Pin<&mut ffi::RenderFrameHostForWebContentsCpp>,
+) -> *mut ffi::content::WebContentsObserver {
+    // This horrid code will all go away once we implement
+    // https://github.com/google/autocxx/issues/592; safe wrappers will
+    // be automatically generated to allow upcasting to superclasses.
+    // NB this code is probably actually _wrong_ too meanwhile; we need to cast
+    // on the C++ side.
+    let subclass_obs_ptr =
+        unsafe { Pin::into_inner_unchecked(obs) } as *mut ffi::RenderFrameHostForWebContentsCpp;
+    unsafe {
+        std::mem::transmute::<
+            *mut ffi::RenderFrameHostForWebContentsCpp,
+            *mut ffi::content::WebContentsObserver,
+        >(subclass_obs_ptr)
+    }
+}