1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Represents the browser side of the browser <--> renderer communication
// channel. There will be one RenderProcessHost per renderer process.
#include "chrome/browser/renderer_host/browser_render_process_host.h"
#include "build/build_config.h"
#include <algorithm>
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
#include "base/command_line.h"
#include "base/linked_ptr.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/scoped_ptr.h"
#include "base/shared_memory.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_helper.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/renderer_security_policy.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/browser/visitedlink_master.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/child_process_info.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/result_codes.h"
#include "chrome/renderer/render_process.h"
#include "grit/generated_resources.h"
using WebKit::WebCache;
#if defined(OS_WIN)
// TODO(port): see comment by the only usage of RenderViewHost in this file.
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/spellchecker.h"
// Once the above TODO is finished, then this block is all Windows-specific
// files.
#include "base/win_util.h"
#include "chrome/browser/sandbox_policy.h"
#include "sandbox/src/sandbox.h"
#elif defined(OS_POSIX)
// TODO(port): Remove temporary scaffolding after porting the above headers.
#include "chrome/common/temp_scaffolding_stubs.h"
#endif
#include "skia/include/SkBitmap.h"
// This class creates the IO thread for the renderer when running in
// single-process mode. It's not used in multi-process mode.
class RendererMainThread : public base::Thread {
public:
explicit RendererMainThread(const std::wstring& channel_id)
: base::Thread("Chrome_InProcRendererThread"),
channel_id_(channel_id),
render_process_(NULL) {
}
~RendererMainThread() {
Stop();
}
protected:
virtual void Init() {
#if defined(OS_WIN)
CoInitialize(NULL);
#endif
render_process_ = new RenderProcess(channel_id_);
// It's a little lame to manually set this flag. But the single process
// RendererThread will receive the WM_QUIT. We don't need to assert on
// this thread, so just force the flag manually.
// If we want to avoid this, we could create the InProcRendererThread
// directly with _beginthreadex() rather than using the Thread class.
base::Thread::SetThreadWasQuitProperly(true);
}
virtual void CleanUp() {
delete render_process_;
#if defined(OS_WIN)
CoUninitialize();
#endif
}
private:
std::wstring channel_id_;
// Deleted in CleanUp() on the renderer thread, so don't use a smart pointer.
RenderProcess* render_process_;
};
// Used for a View_ID where the renderer has not been attached yet
const int32 kInvalidViewID = -1;
// Get the path to the renderer executable, which is the same as the
// current executable.
bool GetRendererPath(std::wstring* cmd_line) {
return PathService::Get(base::FILE_EXE, cmd_line);
}
BrowserRenderProcessHost::BrowserRenderProcessHost(Profile* profile)
: RenderProcessHost(profile),
visible_widgets_(0),
backgrounded_(true),
ALLOW_THIS_IN_INITIALIZER_LIST(cached_dibs_cleaner_(
base::TimeDelta::FromSeconds(5),
this, &BrowserRenderProcessHost::ClearTransportDIBCache)) {
widget_helper_ = new RenderWidgetHelper();
NotificationService::current()->AddObserver(this,
NotificationType::USER_SCRIPTS_LOADED,
NotificationService::AllSources());
if (run_renderer_in_process()) {
// We need a "renderer pid", but we don't have one when there's no renderer
// process. So pick a value that won't clash with other child process pids.
// Linux has PID_MAX_LIMIT which is 2^22. Windows always uses pids that are
// divisible by 4. So...
static int next_pid = 4 * 1024 * 1024;
next_pid += 3;
SetProcessID(next_pid);
}
// Note: When we create the BrowserRenderProcessHost, it's technically
// backgrounded, because it has no visible listeners. But the process
// doesn't actually exist yet, so we'll Background it later, after
// creation.
}
BrowserRenderProcessHost::~BrowserRenderProcessHost() {
if (pid() >= 0) {
WebCacheManager::GetInstance()->Remove(pid());
RendererSecurityPolicy::GetInstance()->Remove(pid());
}
// We may have some unsent messages at this point, but that's OK.
channel_.reset();
// Destroy the AudioRendererHost properly.
if (audio_renderer_host_.get())
audio_renderer_host_->Destroy();
if (process_.handle() && !run_renderer_in_process()) {
ProcessWatcher::EnsureProcessTerminated(process_.handle());
}
NotificationService::current()->RemoveObserver(this,
NotificationType::USER_SCRIPTS_LOADED, NotificationService::AllSources());
ClearTransportDIBCache();
}
bool BrowserRenderProcessHost::Init() {
// calling Init() more than once does nothing, this makes it more convenient
// for the view host which may not be sure in some cases
if (channel_.get())
return true;
// run the IPC channel on the shared IO thread.
base::Thread* io_thread = g_browser_process->io_thread();
// Construct the AudioRendererHost with the IO thread.
audio_renderer_host_ =
new AudioRendererHost(io_thread->message_loop());
scoped_refptr<ResourceMessageFilter> resource_message_filter =
new ResourceMessageFilter(g_browser_process->resource_dispatcher_host(),
audio_renderer_host_.get(),
PluginService::GetInstance(),
g_browser_process->print_job_manager(),
profile(),
widget_helper_,
profile()->GetSpellChecker());
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
// setup IPC channel
const std::wstring channel_id =
ChildProcessInfo::GenerateRandomChannelID(this);
channel_.reset(
new IPC::SyncChannel(channel_id, IPC::Channel::MODE_SERVER, this,
resource_message_filter,
io_thread->message_loop(), true,
g_browser_process->shutdown_event()));
// As a preventive mesure, we DCHECK if someone sends a synchronous message
// with no time-out, which in the context of the browser process we should not
// be doing.
channel_->set_sync_messages_with_no_timeout_allowed(false);
// Build command line for renderer, we have to quote the executable name to
// deal with spaces.
std::wstring renderer_path =
browser_command_line.GetSwitchValue(switches::kBrowserSubprocessPath);
if (renderer_path.empty()) {
if (!GetRendererPath(&renderer_path)) {
// Need to reset the channel we created above or others might think the
// connection is live.
channel_.reset();
return false;
}
}
CommandLine cmd_line(renderer_path);
if (logging::DialogsAreSuppressed())
cmd_line.AppendSwitch(switches::kNoErrorDialogs);
// propagate the following switches to the renderer command line
// (along with any associated values) if present in the browser command line
static const wchar_t* const switch_names[] = {
switches::kRendererAssertTest,
switches::kRendererCrashTest,
switches::kRendererStartupDialog,
switches::kNoSandbox,
switches::kTestSandbox,
#if !defined (GOOGLE_CHROME_BUILD)
// This is an unsupported and not fully tested mode, so don't enable it for
// official Chrome builds.
switches::kInProcessPlugins,
#endif
switches::kDomAutomationController,
switches::kUserAgent,
switches::kJavaScriptFlags,
switches::kRecordMode,
switches::kPlaybackMode,
switches::kNoJsRandomness,
switches::kDisableBreakpad,
switches::kFullMemoryCrashReport,
switches::kEnableLogging,
switches::kDumpHistogramsOnExit,
switches::kDisableLogging,
switches::kLoggingLevel,
switches::kDebugPrint,
switches::kAllowAllActiveX,
switches::kMemoryProfiling,
switches::kEnableWatchdog,
switches::kMessageLoopHistogrammer,
switches::kEnableDCHECK,
switches::kSilentDumpOnDCHECK,
switches::kUseLowFragHeapCrt,
switches::kEnableWebWorkers,
switches::kEnableStatsTable,
switches::kEnableExtensions,
switches::kDisableOutOfProcessDevTools,
switches::kAutoSpellCorrect,
switches::kDisableAudio,
switches::kSimpleDataSource,
};
for (size_t i = 0; i < arraysize(switch_names); ++i) {
if (browser_command_line.HasSwitch(switch_names[i])) {
cmd_line.AppendSwitchWithValue(switch_names[i],
browser_command_line.GetSwitchValue(switch_names[i]));
}
}
// Pass on the browser locale.
const std::wstring locale = g_browser_process->GetApplicationLocale();
cmd_line.AppendSwitchWithValue(switches::kLang, locale);
#if defined(OS_POSIX)
if (browser_command_line.HasSwitch(switches::kRendererCmdPrefix)) {
// launch the renderer child with some prefix (usually "gdb --args")
const std::wstring prefix =
browser_command_line.GetSwitchValue(switches::kRendererCmdPrefix);
cmd_line.PrependWrapper(prefix);
}
#endif // OS_POSIX
cmd_line.AppendSwitchWithValue(switches::kProcessType,
switches::kRendererProcess);
cmd_line.AppendSwitchWithValue(switches::kProcessChannelID,
channel_id);
const std::wstring& profile_path =
browser_command_line.GetSwitchValue(switches::kUserDataDir);
if (!profile_path.empty())
cmd_line.AppendSwitchWithValue(switches::kUserDataDir,
profile_path);
if (run_renderer_in_process()) {
// Crank up a thread and run the initialization there. With the way that
// messages flow between the browser and renderer, this thread is required
// to prevent a deadlock in single-process mode. When using multiple
// processes, the primordial thread in the renderer process has a message
// loop which is used for sending messages asynchronously to the io thread
// in the browser process. If we don't create this thread, then the
// RenderThread is both responsible for rendering and also for
// communicating IO. This can lead to deadlocks where the RenderThread is
// waiting for the IO to complete, while the browsermain is trying to pass
// an event to the RenderThread.
in_process_renderer_.reset(new RendererMainThread(channel_id));
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
in_process_renderer_->StartWithOptions(options);
} else {
base::ProcessHandle process = 0;
#if defined(OS_WIN)
process = sandbox::StartProcess(&cmd_line);
#else
// NOTE: This code is duplicated with plugin_process_host.cc, but
// there's not a good place to de-duplicate it.
base::file_handle_mapping_vector fds_to_map;
int src_fd = -1, dest_fd = -1;
channel_->GetClientFileDescriptorMapping(&src_fd, &dest_fd);
if (src_fd > -1)
fds_to_map.push_back(std::pair<int, int>(src_fd, dest_fd));
base::LaunchApp(cmd_line.argv(), fds_to_map, false, &process);
#endif
if (!process) {
channel_.reset();
return false;
}
process_.set_handle(process);
SetProcessID(process_.pid());
}
resource_message_filter->Init(pid());
WebCacheManager::GetInstance()->Add(pid());
RendererSecurityPolicy::GetInstance()->Add(pid());
// Now that the process is created, set its backgrounding accordingly.
SetBackgrounded(backgrounded_);
InitVisitedLinks();
InitUserScripts();
InitExtensions();
if (max_page_id_ != -1)
channel_->Send(new ViewMsg_SetNextPageID(max_page_id_ + 1));
return true;
}
int BrowserRenderProcessHost::GetNextRoutingID() {
return widget_helper_->GetNextRoutingID();
}
void BrowserRenderProcessHost::CancelResourceRequests(int render_widget_id) {
widget_helper_->CancelResourceRequests(render_widget_id);
}
void BrowserRenderProcessHost::CrossSiteClosePageACK(
int new_render_process_host_id,
int new_request_id) {
widget_helper_->CrossSiteClosePageACK(new_render_process_host_id,
new_request_id);
}
bool BrowserRenderProcessHost::WaitForPaintMsg(int render_widget_id,
const base::TimeDelta& max_delay,
IPC::Message* msg) {
return widget_helper_->WaitForPaintMsg(render_widget_id, max_delay, msg);
}
void BrowserRenderProcessHost::ReceivedBadMessage(uint16 msg_type) {
BadMessageTerminateProcess(msg_type, process_.handle());
}
void BrowserRenderProcessHost::WidgetRestored() {
// Verify we were properly backgrounded.
DCHECK(backgrounded_ == (visible_widgets_ == 0));
visible_widgets_++;
SetBackgrounded(false);
}
void BrowserRenderProcessHost::WidgetHidden() {
// On startup, the browser will call Hide
if (backgrounded_)
return;
DCHECK(backgrounded_ == (visible_widgets_ == 0));
visible_widgets_--;
DCHECK(visible_widgets_ >= 0);
if (visible_widgets_ == 0) {
DCHECK(!backgrounded_);
SetBackgrounded(true);
}
}
void BrowserRenderProcessHost::AddWord(const std::wstring& word) {
#if !defined(OS_WIN)
// TODO(port): reimplement when we get the spell checker up and running on
// other platforms.
NOTIMPLEMENTED();
#else
base::Thread* io_thread = g_browser_process->io_thread();
if (profile()->GetSpellChecker()) {
io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
profile()->GetSpellChecker(), &SpellChecker::AddWord, word));
}
#endif // !defined(OS_WIN)
}
base::ProcessHandle BrowserRenderProcessHost::GetRendererProcessHandle() {
if (run_renderer_in_process())
return base::Process::Current().handle();
return process_.handle();
}
void BrowserRenderProcessHost::InitVisitedLinks() {
VisitedLinkMaster* visitedlink_master = profile()->GetVisitedLinkMaster();
if (!visitedlink_master) {
return;
}
base::SharedMemoryHandle handle_for_process;
bool r = visitedlink_master->ShareToProcess(GetRendererProcessHandle(),
&handle_for_process);
DCHECK(r);
if (base::SharedMemory::IsHandleValid(handle_for_process)) {
channel_->Send(new ViewMsg_VisitedLink_NewTable(handle_for_process));
}
}
void BrowserRenderProcessHost::InitUserScripts() {
UserScriptMaster* user_script_master = profile()->GetUserScriptMaster();
DCHECK(user_script_master);
if (!user_script_master->ScriptsReady()) {
// No scripts ready. :(
return;
}
// Update the renderer process with the current scripts.
SendUserScriptsUpdate(user_script_master->GetSharedMemory());
}
void BrowserRenderProcessHost::InitExtensions() {
// TODO(aa): Should only bother sending these function names if this is an
// extension process.
std::vector<std::string> function_names;
ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names);
Send(new ViewMsg_Extension_SetFunctionNames(function_names));
}
void BrowserRenderProcessHost::SendUserScriptsUpdate(
base::SharedMemory *shared_memory) {
base::SharedMemoryHandle handle_for_process;
bool r = shared_memory->ShareToProcess(GetRendererProcessHandle(),
&handle_for_process);
DCHECK(r);
if (base::SharedMemory::IsHandleValid(handle_for_process)) {
channel_->Send(new ViewMsg_UserScripts_NewScripts(handle_for_process));
}
}
bool BrowserRenderProcessHost::FastShutdownIfPossible() {
if (!process_.handle())
return false; // Render process is probably crashed.
if (BrowserRenderProcessHost::run_renderer_in_process())
return false; // Since process mode can't do fast shutdown.
// Test if there's an unload listener.
// NOTE: It's possible that an onunload listener may be installed
// while we're shutting down, so there's a small race here. Given that
// the window is small, it's unlikely that the web page has much
// state that will be lost by not calling its unload handlers properly.
if (!sudden_termination_allowed())
return false;
// Check for any external tab containers, since they may still be running even
// though this window closed.
BrowserRenderProcessHost::listeners_iterator iter;
// NOTE: This is a bit dangerous. We know that for now, listeners are
// always RenderWidgetHosts. But in theory, they don't have to be.
for (iter = listeners_begin(); iter != listeners_end(); ++iter) {
RenderWidgetHost* widget = static_cast<RenderWidgetHost*>(iter->second);
DCHECK(widget);
if (!widget || !widget->IsRenderView())
continue;
RenderViewHost* rvh = static_cast<RenderViewHost*>(widget);
if (rvh->delegate()->IsExternalTabContainer())
return false;
}
// Otherwise, we're allowed to just terminate the process. Using exit code 0
// means that UMA won't treat this as a renderer crash.
process_.Terminate(ResultCodes::NORMAL_EXIT);
return true;
}
// This is a platform specific function for mapping a transport DIB given its id
TransportDIB* BrowserRenderProcessHost::MapTransportDIB(
TransportDIB::Id dib_id) {
#if defined(OS_WIN)
// On Windows we need to duplicate the handle from the remote process
HANDLE section = win_util::GetSectionFromProcess(
dib_id.handle, GetRendererProcessHandle(), false /* read write */);
return TransportDIB::Map(section);
#elif defined(OS_MACOSX)
// On OSX, the browser allocates all DIBs and keeps a file descriptor around
// for each.
return widget_helper_->MapTransportDIB(dib_id);
#elif defined(OS_LINUX)
return TransportDIB::Map(dib_id);
#endif // defined(OS_LINUX)
}
TransportDIB* BrowserRenderProcessHost::GetTransportDIB(
TransportDIB::Id dib_id) {
const std::map<TransportDIB::Id, TransportDIB*>::iterator
i = cached_dibs_.find(dib_id);
if (i != cached_dibs_.end()) {
cached_dibs_cleaner_.Reset();
return i->second;
}
TransportDIB* dib = MapTransportDIB(dib_id);
if (!dib)
return NULL;
if (cached_dibs_.size() >= MAX_MAPPED_TRANSPORT_DIBS) {
// Clean a single entry from the cache
std::map<TransportDIB::Id, TransportDIB*>::iterator smallest_iterator;
size_t smallest_size = std::numeric_limits<size_t>::max();
for (std::map<TransportDIB::Id, TransportDIB*>::iterator
i = cached_dibs_.begin(); i != cached_dibs_.end(); ++i) {
if (i->second->size() <= smallest_size) {
smallest_iterator = i;
smallest_size = i->second->size();
}
}
delete smallest_iterator->second;
cached_dibs_.erase(smallest_iterator);
}
cached_dibs_[dib_id] = dib;
cached_dibs_cleaner_.Reset();
return dib;
}
void BrowserRenderProcessHost::ClearTransportDIBCache() {
for (std::map<TransportDIB::Id, TransportDIB*>::iterator
i = cached_dibs_.begin(); i != cached_dibs_.end(); ++i) {
delete i->second;
}
cached_dibs_.clear();
}
bool BrowserRenderProcessHost::Send(IPC::Message* msg) {
if (!channel_.get()) {
delete msg;
return false;
}
return channel_->Send(msg);
}
void BrowserRenderProcessHost::OnMessageReceived(const IPC::Message& msg) {
if (msg.routing_id() == MSG_ROUTING_CONTROL) {
// dispatch control messages
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(BrowserRenderProcessHost, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_PageContents, OnPageContents)
IPC_MESSAGE_HANDLER(ViewHostMsg_UpdatedCacheStats,
OnUpdatedCacheStats)
IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
SuddenTerminationChanged);
IPC_MESSAGE_HANDLER(ViewHostMsg_ExtensionAddListener,
OnExtensionAddListener)
IPC_MESSAGE_HANDLER(ViewHostMsg_ExtensionRemoveListener,
OnExtensionRemoveListener)
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP_EX()
if (!msg_is_ok) {
// The message had a handler, but its de-serialization failed.
// We consider this a capital crime. Kill the renderer if we have one.
ReceivedBadMessage(msg.type());
}
return;
}
// dispatch incoming messages to the appropriate TabContents
IPC::Channel::Listener* listener = GetListenerByID(msg.routing_id());
if (!listener) {
if (msg.is_sync()) {
// The listener has gone away, so we must respond or else the caller will
// hang waiting for a reply.
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
reply->set_reply_error();
Send(reply);
}
return;
}
listener->OnMessageReceived(msg);
}
void BrowserRenderProcessHost::OnChannelConnected(int32 peer_pid) {
// process_ is not NULL if we created the renderer process
if (!process_.handle()) {
if (base::GetCurrentProcId() == peer_pid) {
// We are in single-process mode. In theory we should have access to
// ourself but it may happen that we don't.
process_.set_handle(base::GetCurrentProcessHandle());
} else {
#if defined(OS_WIN)
// Request MAXIMUM_ALLOWED to match the access a handle
// returned by CreateProcess() has to the process object.
process_.set_handle(OpenProcess(MAXIMUM_ALLOWED, FALSE, peer_pid));
#elif defined(OS_POSIX)
// ProcessHandle is just a pid.
process_.set_handle(peer_pid);
#endif
DCHECK(process_.handle());
}
} else {
// Need to verify that the peer_pid is actually the process we know, if
// it is not, we need to panic now. See bug 1002150.
if (peer_pid != process_.pid()) {
// In the case that we are running the renderer in a wrapper, this check
// is invalid as it's the wrapper PID that we'll have, not the actual
// renderer
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
if (cmd_line.HasSwitch(switches::kRendererCmdPrefix))
return;
CHECK(peer_pid == process_.pid());
}
}
}
// Static. This function can be called from the IO Thread or from the UI thread.
void BrowserRenderProcessHost::BadMessageTerminateProcess(
uint16 msg_type,
base::ProcessHandle process) {
LOG(ERROR) << "bad message " << msg_type << " terminating renderer.";
if (BrowserRenderProcessHost::run_renderer_in_process()) {
// In single process mode it is better if we don't suicide but just crash.
CHECK(false);
}
NOTREACHED();
base::KillProcess(process, ResultCodes::KILLED_BAD_MESSAGE, false);
}
void BrowserRenderProcessHost::OnChannelError() {
// Our child process has died. If we didn't expect it, it's a crash.
// In any case, we need to let everyone know it's gone.
DCHECK(process_.handle());
DCHECK(channel_.get());
bool child_exited;
bool did_crash = base::DidProcessCrash(&child_exited, process_.handle());
NotificationService::current()->Notify(
NotificationType::RENDERER_PROCESS_CLOSED,
Source<RenderProcessHost>(this),
Details<bool>(&did_crash));
// POSIX: If the process crashed, then the kernel closed the socket for it
// and so the child has already died by the time we get here. Since
// DidProcessCrash called waitpid with WNOHANG, it'll reap the process.
// However, if DidProcessCrash didn't reap the child, we'll need to in
// ~BrowserRenderProcessHost via ProcessWatcher. So we can't close the handle
// here.
//
// This is moot on Windows where |child_exited| will always be true.
if (child_exited)
process_.Close();
channel_.reset();
// This process should detach all the listeners, causing the object to be
// deleted. We therefore need a stack copy of the web view list to avoid
// crashing when checking for the termination condition the last time.
IDMap<IPC::Channel::Listener> local_listeners(listeners_);
for (listeners_iterator i = local_listeners.begin();
i != local_listeners.end(); ++i) {
i->second->OnMessageReceived(ViewHostMsg_RenderViewGone(i->first));
}
ClearTransportDIBCache();
// this object is not deleted at this point and may be reused later.
// TODO(darin): clean this up
}
void BrowserRenderProcessHost::OnPageContents(const GURL& url,
int32 page_id,
const std::wstring& contents) {
Profile* p = profile();
if (!p || p->IsOffTheRecord())
return;
HistoryService* hs = p->GetHistoryService(Profile::IMPLICIT_ACCESS);
if (hs)
hs->SetPageContents(url, contents);
}
void BrowserRenderProcessHost::OnUpdatedCacheStats(
const WebCache::UsageStats& stats) {
WebCacheManager::GetInstance()->ObserveStats(pid(), stats);
}
void BrowserRenderProcessHost::SuddenTerminationChanged(bool enabled) {
set_sudden_termination_allowed(enabled);
}
void BrowserRenderProcessHost::SetBackgrounded(bool backgrounded) {
// If the process_ is NULL, the process hasn't been created yet.
if (process_.handle()) {
bool should_set_backgrounded = true;
#if defined(OS_WIN)
// The cbstext.dll loads as a global GetMessage hook in the browser process
// and intercepts/unintercepts the kernel32 API SetPriorityClass in a
// background thread. If the UI thread invokes this API just when it is
// intercepted the stack is messed up on return from the interceptor
// which causes random crashes in the browser process. Our hack for now
// is to not invoke the SetPriorityClass API if the dll is loaded.
should_set_backgrounded = (GetModuleHandle(L"cbstext.dll") == NULL);
#endif // OS_WIN
if (should_set_backgrounded) {
bool rv = process_.SetProcessBackgrounded(backgrounded);
if (!rv) {
return;
}
}
// Now tune the memory footprint of the renderer.
// If the OS needs to page, we'd rather it page idle renderers.
BrowserProcess::MemoryModel model = g_browser_process->memory_model();
if (model < BrowserProcess::HIGH_MEMORY_MODEL) {
if (backgrounded) {
if (model == BrowserProcess::LOW_MEMORY_MODEL)
process_.EmptyWorkingSet();
else if (model == BrowserProcess::MEDIUM_MEMORY_MODEL)
process_.ReduceWorkingSet();
} else {
if (model == BrowserProcess::MEDIUM_MEMORY_MODEL)
process_.UnReduceWorkingSet();
}
}
}
// Note: we always set the backgrounded_ value. If the process is NULL
// (and hence hasn't been created yet), we will set the process priority
// later when we create the process.
backgrounded_ = backgrounded;
}
// NotificationObserver implementation.
void BrowserRenderProcessHost::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::USER_SCRIPTS_LOADED: {
base::SharedMemory* shared_memory =
Details<base::SharedMemory>(details).ptr();
if (shared_memory) {
SendUserScriptsUpdate(shared_memory);
}
break;
}
default: {
NOTREACHED();
break;
}
}
}
void BrowserRenderProcessHost::OnExtensionAddListener(
const std::string& event_name) {
URLRequestContext* context = profile()->GetRequestContext();
ExtensionMessageService* ems = ExtensionMessageService::GetInstance(context);
ems->AddEventListener(event_name, pid());
}
void BrowserRenderProcessHost::OnExtensionRemoveListener(
const std::string& event_name) {
URLRequestContext* context = profile()->GetRequestContext();
ExtensionMessageService* ems = ExtensionMessageService::GetInstance(context);
ems->RemoveEventListener(event_name, pid());
}
|