8000 browser: make destruction of webContents async by deepak1556 · Pull Request #9113 · electron/electron · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

browser: make destruction of webContents async #9113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 1, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion atom/browser/api/atom_api_browser_view.cc
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ void BrowserView::Init(v8::Isolate* isolate,
}

BrowserView::~BrowserView() {
api_web_contents_->DestroyWebContents();
api_web_contents_->DestroyWebContents(true /* async */);
}

// static
Expand Down
27 changes: 19 additions & 8 deletions atom/browser/api/atom_api_web_contents.cc
Original file line number Diff line number Diff line change
Expand Up @@ -417,15 +417,28 @@ WebContents::~WebContents() {
guest_delegate_->Destroy();

RenderViewDelete 8000 d(web_contents()->GetRenderViewHost());
DestroyWebContents();

if (type_ == WEB_VIEW) {
DestroyWebContents(false /* async */);
} else {
if (type_ == BROWSER_WINDOW && owner_window()) {
owner_window()->CloseContents(nullptr);
} else {
DestroyWebContents(true /* async */);
}
// The WebContentsDestroyed will not be called automatically because we
// destroy the webContents in the next tick. So we have to manually
// call it here to make sure "destroyed" event is emitted.
WebContentsDestroyed();
}
}
}

void WebContents::DestroyWebContents() {
void WebContents::DestroyWebContents(bool async) {
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
ResetManagedWebContents();
ResetManagedWebContents(async);
}

bool WebContents::DidAddMessageToConsole(content::WebContents* source,
Expand Down Expand Up @@ -477,7 +490,7 @@ void WebContents::AddNewContents(content::WebContents* source,
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
initial_rect.x(), initial_rect.y(), initial_rect.width(),
initial_rect.height())) {
api_web_contents->DestroyWebContents();
api_web_contents->DestroyWebContents(true /* async */);
}
}

Expand Down Expand Up @@ -816,10 +829,8 @@ void WebContents::DidFinishNavigation(

void WebContents::TitleWasSet(content::NavigationEntry* entry,
bool explicit_set) {
if (entry)
Emit("-page-title-updated", entry->GetTitle(), explicit_set);
else
Emit("-page-title-updated", "", explicit_set);
auto title = entry ? entry->GetTitle() : base::string16();
Emit("page-title-updated", title, explicit_set);
}

void WebContents::DidUpdateFaviconURL(
Expand Down
2 changes: 1 addition & 1 deletion atom/browser/api/atom_api_web_contents.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
v8::Local<v8::FunctionTemplate> prototype);

// Notifies to destroy any guest web contents before destroying self.
void DestroyWebContents();
void DestroyWebContents(bool async);

int64_t GetID() const;
int GetProcessID() const;
Expand Down
2 changes: 1 addition & 1 deletion atom/browser/api/atom_api_window.cc
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ void Window::WillDestroyNativeObject() {
}

void Window::OnWindowClosed() {
api_web_contents_->DestroyWebContents();
api_web_contents_->DestroyWebContents(true /* async */);

RemoveFromWeakMap();
window_->RemoveObserver(this);
Expand Down
9 changes: 7 additions & 2 deletions atom/browser/common_web_contents_delegate.cc
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,13 @@ void CommonWebContentsDelegate::SetOwnerWindow(
}
}

void CommonWebContentsDelegate::ResetManagedWebContents() {
web_contents_.reset();
void CommonWebContentsDelegate::ResetManagedWebContents(bool async) {
if (async) {
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE,
web_contents_.release());
} else {
web_contents_.reset();
}
}

content::WebContents* CommonWebContentsDelegate::GetWebContents() const {
Expand Down
2 changes: 1 addition & 1 deletion atom/browser/common_web_contents_delegate.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class CommonWebContentsDelegate
#endif

// Destroy the managed InspectableWebContents object.
void ResetManagedWebContents();
void ResetManagedWebContents(bool async);

private:
// Callback for when DevToolsSaveToFile has completed.
Expand Down
6 changes: 1 addition & 5 deletions lib/browser/api/browser-window.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,9 @@ BrowserWindow.prototype._init = function () {

// Change window title to page title.
this.webContents.on('page-title-updated', (event, title) => {
// The page-title-updated event is not emitted immediately (see #3645), so
// when the callback is called the BrowserWindow might have been closed.
if (this.isDestroyed()) return

// Route the event to BrowserWindow.
this.emit('page-title-updated', event, title)
if (!event.defaultPrevented) this.setTitle(title)
if (!this.isDestroyed() && !event.defaultPrevented) this.setTitle(title)
})

// Sometimes the webContents doesn't get focus when window is shown, so we
Expand Down
7 changes: 0 additions & 7 deletions lib/browser/api/web-contents.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,13 +268,6 @@ WebContents.prototype._init = function () {
this.reload()
})

// Delays the page-title-updated event to next tick.
this.on('-page-title-updated', function (...args) {
setImmediate(() => {
this.emit('page-title-updated', ...args)
})
})

app.emit('web-contents-created', {}, this)
}

Expand Down
68 changes: 68 additions & 0 deletions spec/api-browser-window-spec.js
F438
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,42 @@ describe('BrowserWindow module', function () {
})

describe('BrowserWindow.close()', function () {
let server

before(function (done) {
server = http.createServer((request, response) => {
switch (request.url) {
case '/404':
response.statusCode = '404'
response.end()
break
case '/301':
response.statusCode = '301'
response.setHeader('Location', '/200')
response.end()
break
case '/200':
response.statusCode = '200'
response.end('hello')
break
case '/title':
response.statusCode = '200'
response.end('<title>Hello</title>')
break
default:
done('unsupported endpoint')
}
}).listen(0, '127.0.0.1', () => {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})

after(function () {
server.close()
server = null
})

it('should emit unload handler', function (done) {
w.webContents.on('did-finish-load', function () {
w.close()
Expand All @@ -109,6 +145,38 @@ describe('BrowserWindow module', function () {
})
w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false.html'))
})

it('should not crash when invoked synchronously inside navigation observer', function (done) {
const events = [
{ name: 'did-start-loading', url: `${server.url}/200` },
{ name: 'did-get-redirect-request', url: `${server.url}/301` },
{ name: 'did-get-response-details', url: `${server.url}/200` },
{ name: 'dom-ready', url: `${server.url}/200` },
{ name: 'page-title-updated', url: `${server.url}/title` },
{ name: 'did-stop-loading', url: `${server.url}/200` },
{ name: 'did-finish-load', url: `${server.url}/200` },
{ name: 'did-frame-finish-load', url: `${server.url}/200` },
{ name: 'did-fail-load', url: `${server.url}/404` }
]
const responseEvent = 'window-webContents-destroyed'

function* genNavigationEvent () {
let eventOptions = null
while ((eventOptions = events.shift()) && events.length) {
let w = new BrowserWindow({show: false})
eventOptions.id = w.id
eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
yield 1
}
}

let gen = genNavigationEvent()
ipcRenderer.on(responseEvent, function () {
if (!gen.next().value) done()
})
gen.next()
})
})

describe('window.close()', function () {
Expand Down
66 changes: 66 additions & 0 deletions spec/api-web-contents-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -542,4 +542,70 @@ describe('webContents module', function () {
})
})
})

describe('destroy()', () => {
let server

before(function (done) {
server = http.createServer((request, response) => {
switch (request.url) {
case '/404':
response.statusCode = '404'
response.end()
break
case '/301':
response.statusCode = '301'
response.setHeader('Location', '/200')
response.end()
break
case '/200':
response.statusCode = '200'
response.end('hello')
break
default:
done('unsupported endpoint')
}
}).listen(0, '127.0.0.1', () => {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})

after(function () {
server.close()
server = null
})

it('should not crash when invoked synchronously inside navigation observer', (done) => {
const events = [
{ name: 'did-start-loading', url: `${server.url}/200` },
{ name: 'did-get-redirect-request', url: `${server.url}/301` },
{ name: 'did-get-response-details', url: `${server.url}/200` },
{ name: 'dom-ready', url: `${server.url}/200` },
{ name: 'did-stop-loading', url: `${server.url}/200` },
{ name: 'did-finish-load', url: `${server.url}/200` },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
// { name: 'did-frame-finish-load', url: `${server.url}/200` },
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zcbenz currently we have in api_web_contents.cc the following:

void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
                                const GURL& validated_url) {
  bool is_main_frame = !render_frame_host->GetParent();
  Emit("did-frame-finish-load", is_main_frame);

  if (is_main_frame)
    Emit("did-finish-load");
}

calling webContents.destroy inside did-frame-finish-load will lead to a crash when did-finish-load is invoked with

[2853:0404/235125.714735:FATAL:wrappable.cc(24)] Check failed: !wrapper_.IsEmpty(). 
#0 0x7fe05839616e base::debug::StackTrace::StackTrace()
#1 0x7fe0583b2eab logging::LogMessage::~LogMessage()
#2 0x000000b8d723 mate::WrappableBase::GetWrapper()
#3 0x000000c782e5 mate::EventEmitter<>::GetWrapper()
#4 0x000000c7b1f9 _ZN4mate12EventEmitterIN4atom3api11WebContentsEE14EmitWithSenderIJEEEbRKN4base16BasicStringPieceISsEEPN7content11WebContentsEPN3IPC7MessageEDpRKT_
#5 0x000000c71bf4 _ZN4mate12EventEmitterIN4atom3api11WebContentsEE4EmitIJEEEbRKN4base16BasicStringPieceISsEEDpRKT_
#6 0x000000c6761a atom::api::WebContents::DidFinishLoad()
#7 0x7fe05c397999 content::WebContentsImpl::OnDidFinishLoad()
#8 0x7fe05c39777e <unknown>
#9 0x7fe05c3963fc content::WebContentsImpl::OnMessageReceived()
#10 0x7fe05c121888 content::RenderFrameHostImpl::OnMessageReceived()
#11 0x7fe057edeac5 IPC::ChannelProxy::Context::OnDispatchMessage()
#12 0x7fe058396cee base::debug::TaskAnnotator::RunTask()
#13 0x7fe0583bba1c base::MessageLoop::RunTask()
#14 0x7fe0583bbd38 base::MessageLoop::DeferOrRunPendingTask()
#15 0x7fe0583bc0fb base::MessageLoop::DoWork()
#16 0x7fe0583be4aa <unknown>
#17 0x7fe0499835a7 g_main_context_dispatch
#18 0x7fe049983810 <unknown>
#19 0x7fe0499838bc g_main_context_iteration
#20 0x7fe0583be316 base::MessagePumpGlib::Run()
#21 0x7fe0583bb7b7 base::MessageLoop::RunHandler()
#22 0x7fe0583e52b0 base::RunLoop::Run()
#23 0x7fe05c03bab8 content::BrowserMainLoop::MainMessageLoopRun()
#24 0x7fe05c03b905 content::BrowserMainLoop::RunMainMessageLoopParts()
#25 0x7fe05c03e94d <unknown>
#26 0x7fe05c03743e content::BrowserMain()
#27 0x7fe05c6db094 <unknown>
#28 0x7fe05c6d9ba0 content::ContentMain()
#29 0x000000aa569a main
#30 0x7fe047ae9511 __libc_start_main
#31 0x000000aa54e5 <unknown>

I can think of two ways to fix this:

  • Make destroy async by default deepak1556/native-mate@c98d5d6 , will have to rewire cases inside the code base to follow this behavior, especially webview since we need to make sure they are destroyed before any host webContents.

  • Return empty wrapper when its destroyed and check if object is available before emitting events.

What can be the best approach to fix this scenario ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer the second way, making destroy async feels scary.

{ name: 'did-fail-load', url: `${server.url}/404` }
]
const responseEvent = 'webcontents-destroyed'

function* genNavigationEvent () {
let eventOptions = null
while ((eventOptions = events.shift()) && events.length) {
eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
yield 1
}
}

let gen = genNavigationEvent()
ipcRenderer.on(responseEvent, () => {
if (!gen.next().value) done()
})
gen.next()
})
})
})
21 changes: 21 additions & 0 deletions spec/static/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,27 @@ ipcMain.on('crash-service-pid', (event, pid) => {
event.returnValue = null
})

ipcMain.on('test-webcontents-navigation-observer', (event, options) => {
let contents = null
let destroy = () => {}
if (options.id) {
const w = BrowserWindow.fromId(options.id)
contents = w.webContents
destroy = () => w.close()
} else {
contents = webContents.create()
destroy = () => contents.destroy()
}

contents.once(options.name, () => destroy())

contents.once('destroyed', () => {
event.sender.send(options.responseEvent)
})

contents.loadURL(options.url)
})

// Suspend listeners until the next event and then restore them
const suspendListeners = (emitter, eventName, callback) => {
const listeners = emitter.listeners(eventName)
Expand Down
0